冒泡排序 O(N^2)
每次将最大的数冒到最右边
public static void bubbleSort(int[] arr) {
if (arr == null || arr.length <= 0) {
return;
}
for (int e = arr.length-1; e >= 1; --e) {
for (int i=0; i < e; ++i) {
if (arr[i] > arr[e]) {
swap(arr, i, e);
}
}
}
}
public static void swap(int[] arr, int i, int j) {
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
选择排序 O(N^2)
每次选择区间最小位置与目标位置交换
public static void selectionSort(int[] arr) {
for (int i=0; i<arr.length-1; ++i) {
int minIndex = i;
for(int j=i+1; j<arr.length; ++j) {
minIndex = arr[j] < arr[minIndex] ? j : minIndex;
}
swap(arr, i, minIndex);
}
}
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
插入排序 O(N^2)
依次向左比较,看最终能插入到哪个位置
public static void insertionSort(int[] arr) {
for (int i=1; i<arr.length; ++i) {
for (int j=i-1; j>=0 && arr[j]>arr[j+1]; --j) {
swap(arr, j, j+1);
}
}
}
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
归并排序 O(N*log(N))
分治
public static void mergeSort(int[] arr) {
mergeSort(arr,0, arr.length-1);
}
public static void mergeSort(int[] arr, int l, int r) {
if (l == r) {
return ;
}
int mid = l + ((r - l) >> 1);
mergeSort(arr, l, mid);
mergeSort(arr, mid+1, r);
merge(arr, l, mid, r);
}
public static void merge(int[] arr, int l, int mid, int r) {
int[] help = new int[r-l+1];
int p1 = l;
int p2 = mid+1;
int i = 0;
while(p1 <= mid && p2 <= r) {
help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
}
while(p1 <= mid) {
help[i++] = arr[p1++];
}
while(p2 <= r) {
help[i++] = arr[p2++];
}
for (i=0; i < help.length; ++i) {
arr[l+i] = help[i];
}
}