1)插入排序(从第二个元素开始,依次从剩余元素中选择一个,插入到前面有序的子序列中)
public static void insertSort(int[] nums){ if ( nums == null ){ return; } int len = nums.length; int tmp, j; for(int i = 1; i < len; ++i){ tmp = nums[i]; j = i - 1; while( j >= 0 && tmp < nums[j]){ nums[j + 1] = nums[j]; j--; } nums[j + 1] = tmp; } }
2)快速排序(不是稳定的排序,平均时间复杂度O(nlogn))
public void quickSort(int[] a, int low, int high) { if (low < high) { int location = partition(a,low,high); quickSort(a, low, location - 1); quickSort(a, location + 1, high); } } public int partition(int[] a, int left, int right) { if (left < right) { int pivot = a[left]; while(left < right){ while (left < right && a[right] >= pivot) { right--; } a[left] = a[right]; while (left < right && a[left] <= pivot) { left++; } a[right] = a[left]; } a[left] = pivot; } return left; }
3)归并排序(是稳定的排序算法,时间复杂度O(nlogn))
public void mergeSort(int[] a, int low, int high) { if (low < high) { int mid = (low + high) / 2; mergeSort(a, low, mid); mergeSort(a, mid + 1, high); merge(a, low, mid, high); } } public void merge(int[] a, int left, int mid, int right) { if (left < right){ int len = right - left + 1; int[] b = new int[len]; int i = left, j = mid + 1, k = 0; while(i <= mid && j <= right){ if (a[i] <= a[j]) { b[k++] = a[i++]; } else { b[k++] = a[j++]; } } while (i <= mid) { b[k++] = a[i++]; } while (j <= right) { b[k++] = a[j++]; } for (int l = 0; l < k; ++l){ a[l + left] = b[l]; } } }
4)堆排序(不是稳定的排序,时间复杂度O(nlogn))
5)计数排序、基数排序、桶排序。