排序算法
1.快速排序
采用分治策略,O(nlgn);
public class QuickSort { public void quickSort(int[] arr, int low ,int high){ if (low < high){ int index = partition(arr, low , high); quickSort(arr, low, index-1); quickSort(arr, index+1, high); } } public int partition(int[] arr, int low, int high){ int key = arr[low]; while (low < high) { while (low < high && arr[high] > key) high--; arr[low] = arr[high]; while (low < high && arr[low] < key) low++; arr[high] = arr[low]; } arr[low] = key; return low; } }
2. 归并排序
典型的分治思想,将数组分成若干部分,然后两两归并。O(nlgn)
1 public class MergeSort { 2 public void mergeSort(int[] A, int low, int high) { 3 if (low < high){//或者low == high return;长度为1时停止递归 4 int mid = (low+high)/2; 5 mergeSort(A, low, mid); 6 mergeSort(A, mid+1, high); 7 merge(A, low, high, mid); 8 } 9 } 10 11 public void merge(int[] A, int low, int high, int mid){ 12 int[] B = new int[A.length]; 13 int i = low; 14 int j = mid+1; 15 int index = 0; 16 while (i <= mid && j <= high){ 17 B[index++] = A[i] < A[j] ? A[i] : A[j]; 18 } 19 while (i <= mid){ 20 B[index++] = A[i++]; 21 } 22 while (j <= mid){ 23 B[index++] = A[j++]; 24 } 25 for (int k = 0; k < A.length; k++) 26 { 27 A[low++] = B[k]; 28 } 29 } 30 }