| 排序方法 | 时间复杂度(平均) | 时间复杂度(最坏) | 时间复杂度(最好) | 空间复杂度 | 稳定性 | 复杂性 |
|---|
| 插入排序 | O(n2) | O(n2) | O(n) | O(1) | 稳定 | 简单 |
| 冒泡排序 | O(n2) | O(n2) | O(n) | O(1) | 不稳定 | 较复杂 |
| 归并排序 | O(nlog2n) | O(nlog2n) | O(nlog2n) | O(n) | 稳定 | 较复杂 |
| 快速排序 | O(nlog2n) | O(n2) | O(nlog2n) | O(nlog2n) | 不稳定 | 较复杂 |
1. 插入排序
public static int[] insertSort(int[] array) {for (int index = 0; index < array.length; index++) {int temp = array[index]; int leftIndex = index - 1;while (leftIndex >= 0 && array[leftIndex] > temp) { array[leftIndex + 1] = array[leftIndex];leftIndex--;}array[leftIndex + 1] = temp;}return array;}
2.冒泡排序
public static void sort(int[] array) {for (int i = 0; i < array.length - 1; i++) {for (int j = 0; j < array.length - 1 - i; j++) {if (array[j] > array[j + 1]) {int temp = array[j];array[j] = array[j + 1];array[j + 1] = temp;}}}}
3.归并排序
public static void mergeArray(int[] array, int low, int mid, int high) {int[] temp = new int[array.length];int i = low; int j = mid + 1; int k = 0;while (i <= mid && j <= high) {if (array[i] > array[j]) temp[k++] = array[j++];else temp[k++] = array[i++];}while (i <= mid) temp[k++] = array[i++];while (j <= high) temp[k++] = array[j++];for (int x = 0; x < k; x++) array[x + low] = temp[x];}public static void mergeSort(int[] array, int low, int high) {if (low < high) {int mid = (low + high) / 2; mergeSort(array, low, mid); mergeSort(array, mid + 1, high); mergeArray(array, low, mid, high); }}
4. 快速排序
public static int getIndex(int[] array, int low, int high) {int temp = array[low]; while (low < high) {while (low < high && array[high] > temp) high--; array[low] = array[high]; while (low < high && array[low] < temp) low++; array[high] = array[low]; }array[low] = temp;return low;}public static void quickSort(int[] array, int low, int high) {if (low < high) {int index = getIndex(array, low, high);quickSort(array, low, index - 1);quickSort(array, index + 1, high);}}
5.测试数据
public static void main(String[] args) {int[] array = {38, 65, 97, 76, 13, 27, 49};insertSort(array);System.out.print("插入排序从小到大排序后的结果是:");for (Integer i : array) {System.out.print(i + " ");}System.out.println();int[] array1 = {38, 65, 97, 76, 13, 27, 49};sort(array1);System.out.print("冒泡排序从小到大排序后的结果是:");for (Integer i : array1) {System.out.print(i + " ");}System.out.println();int[] array2 = {38, 65, 97, 76, 13, 27, 49};mergeSort(array2, 0, array2.length - 1);System.out.print("归并排序从小到大排序后的结果是:");for (Integer i : array2) {System.out.print(i + " ");}System.out.println();int[] array3 = {38, 65, 97, 76, 13, 27, 49};quickSort(array3, 0, array3.length - 1);System.out.print("快速排序从小到大排序后的结果是:");for (Integer i : array3) {System.out.print(i + " ");}}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!