exchange sort
3. Bubble sort
Time complexity: O(n2) O(n) O(n2)
Space complexity: O(1)
Idea: The keywords to be sorted elements are scanned multiple times from back to front, and when the order of two adjacent keywords does not match the sorting rules, the two elements are exchanged. In this way, the element with the smaller keyword is like a bubble, from the back to the front.
Stability: Stable, adjacent keywords are compared pairwise, and if they are equal, they are not exchanged. Therefore, the relative positions of equal numbers before and after sorting remain unchanged.
Code:
public static void bubbleSort(int[] array) {
for (int i = 0; i < array.length; i++) {
/**
* 这边要注意 for (int j = array.length -1; j >= i + 1; j--)。 不要写成
* for (int j = i + 1; j < array.length ; j++)从后往前
*/
for (int j = array.length -1; j >= i + 1; j--) {
if (array[j -1 ] > array[j]) {
//数据交换
int temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
}
4. Quick Sort
Time complexity: O(n2) O(nlogn) O(nlogn)
Space complexity: O(nlogn) for method stacks
Idea: This algorithm is a divide-and-conquer algorithm. First, a reference element is selected, and the sequence to be sorted is divided into two parts according to the reference element. One part is smaller than the reference element, and the other part is greater than or equal to the reference element. At this time, the reference element is correct after it is sorted. position, and then recursively sort the divided two parts in the same way. The selection of the base element has a great impact on the performance of quick sort, so generally you want to shuffle the sorted array to select the first element or randomly select an element from the back to replace the first element as the base element.
Stability: Unstable Quicksort will place keywords greater than or equal to the base element to the right of the base element.
Code:
public
static
void
quickSort(
int
[] arr){
qsort(arr,
0
, arr.length-
1
);
}
private
static
void
qsort(
int
[] arr,
int
low,
int
high){
if
(low < high){
int
temp
= arr[low];
//基准点
while
(low<high){
while
(low<high && arr[high]>=temp) --high;
arr[low]=arr[high];
//交换比基准点小的记录到左端
while
(low<high && arr[low]<=temp) ++low;
arr[high] = arr[low];
//交换比基准点小的记录到右端
}
//扫描完成,基准点与low交换
arr[low] = temp;
return
low;
}
qsort(arr, low, temp-
1
);
//递归排序左子数组
qsort(arr, temp+
1
, high);
//递归排序右子数组
}
}