java五种排序算法汇总工具类
程序员文章站
2022-04-11 18:05:18
...
这个工具类简单明了地总结了java的快速排序,希尔排序,插入排序,堆排序,归并排序五种排序算法,代码中并没有对这几种排序算法的一个说明,关于思想部分希望在自行查阅相关说明,这里只是对这几种算法进行一个概括,以供大家使用。
public class Sort { public static> void insertionSort(AnyType[] a) { insertionSort(a, 0, a.length - 1); } private static > void insertionSort(AnyType[] a, int left, int right) { int j; // 记录第一个比tmp小的元素的后边一位的位置 for (int p = left; p left && tmp.compareTo(a[j - 1]) > void shellSort(AnyType[] arr) { int j; for (int gap = arr.length / 2; gap > 0; gap /= 2) { for (int i = gap; i = gap && tmp.compareTo(arr[j - gap]) > void perculateDown(AnyType[] arr, int i, int size) { AnyType tmp = arr[i]; for (int child; (child = leftChild(i)) > void heapSort(AnyType[] arr) { for (int i = arr.length / 2; i >= 0; i--) { perculateDown(arr, i, arr.length); } for (int i = arr.length - 1; i >= 0; i--) { swapReferences(arr, 0, i); perculateDown(arr, 0, i); } } private static > void swapReferences(AnyType[] arr, int i, int j) { AnyType tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } public static > void mergeSort(AnyType[] arr) { AnyType[] tmp = ((AnyType[]) new Comparable[arr.length]); mergeSort(arr, 0, arr.length - 1, tmp); } private static > void mergeSort(AnyType[] arr, int start, int end, AnyType[] tmp) { if (start > 1; mergeSort(arr, start, mid, tmp); mergeSort(arr, mid + 1, end, tmp); merge(arr, start, mid, end, tmp); } } private static > void merge(AnyType[] arr, int start, int mid, int end, AnyType[] tmp) { int i = start, j = mid + 1, k = start; while (i > void quickSort(AnyType[] arr) { quickSort(arr, 0, arr.length - 1); } private static > void quickSort(AnyType[] arr, int left, int right) { if (left + LENGTH_DIFF 0); if (i > AnyType medium(AnyType[] arr, int left, int right) { int center = (left + right) / 2; if (arr[center].compareTo(arr[left]) 0) { swapReferences(arr, left, right); } if (arr[center].compareTo(arr[right])
下一篇: PHP生圆成球唯一码