You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
in-place and not-in-place: whether the sorting will use additional spaces
stable or unstable: whether the sorting will change the original order of elements that have the same value: 8A 8B -> 8A 8B or 8B 8A?
adaptive or non-adaptive: whether the sorting will take advantage of the already sorted elements
Bubble Sort
Repeatedly compare neighbor pairs and swap if necessary.
In each iteration, check all pairs for whether they need to be swapped. After each swap, the largest element (bubble) in the unsorted part should be moved to the right side.
The sorted parted doesn't change once positioned.
Features
Value
Best Time
O(n)
Worst Time
O(n^2)
Space Complexity
O(1)
Stable
Stable
In place?
Yes
publicstaticint[] bubbleSort(int[] A) {
for (inti = 0; i < A.length - 1; i++) {
for (intj = 0; j < A.length - i - 1; j++) { // The right side of the array is ordered and have no need to checkif (A[j] > A[j + 1]) {
inttemp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
returnA;
}
Selection Sort
Repeatedly select the smallest element in the list and append it to the result (by swapping it with the element in the nth position). 2. The sorted parted doesn't change once positioned.
Always need quadratic number of compares((n-1)+(n-2)+...+2+1=(1/2*n^2)) but only meed liner number of swaps(n).
Features
Value
Best Time
O(n)
Worst Time
O(n^2)
Space Complexity
O(1)
Stable
Unstable
In place?
Yes
publicstaticint[] selectionSort(int[] A) {
for (inti = 0; i < A.length - 1; i++) { // We don't need to check the last element, it will be the largestintmin = i;
for (intj = i + 1; j < A.length; j++) {
if (A[min] > A[j]) {
min = j;
}
}
inttemp = A[i];
A[i] = A[min];
A[min] = temp;
}
returnA;
}
Insertion Sort
Repeatedly add new element to the sorted result.
Take the first element as sorted sub-array and add new element by swaping it to the proper, sorted position.
Could use a fewer number of compares(n) in best cases but more swaps in worst cases(1/2*n^2).
Features
Value
Best Time
O(n)
Worst Time
O(n^2)
Space Complexity
O(1)
Stable
Stable
In place?
Yes
publicstaticint[] insertionSort(int[] A) {
for (inti = 1; i < A.length; i++) {
intcur = A[i];
intj = i - 1;
while (j >= 0 && A[j] > cur) {
A[j + 1] = A[j];
j = j - 1;
}
A[j + 1] = cur;
}
returnA;
}
Merge Sort
Divide, conquer, combine: Dividethe array into one-element-long sub-array, conquer (sort) each sub-array pair, and recursively combine (merge) them together.