Sorting is a famous problem in programming, today I will share the way I have implemented the Bubble Sort Algorithm.
Bubble Sort
Bubble Sort is the algorithm to sort elements in an array by ascending or descending. The algorithm will partition the array into a sorted partition and unsorted partition.
Implementation
The algorithm is very simple, we repeatedly swap the adjacent elements if they are in the wrong order.
Ascending
Init a variable called
lastUnsortedIndex
. Its value is the last index of an unsorted array - which isarr.length - 1
.We are going to compare two values of the current index and the next index, so we will need two loops. The first loop will start increasing from 0 to
lastUnsortedIndex
, the second loop will start increasing from 0 to the index beforelastUnsortedIndex
which islastUnsortedIndex - i
(i is the index from the first loop). Swap the values if the current index greater than the next index.The algorithm ends when i == lastUnsortedIndex
The sorted array direction is ascending
Implementation
1 | int arr[] = {100, 2, -2, 5, -10, 1} |