Java-时间复杂度为O(nlogn)的排序算法(快速排序, 归并排序, 堆排序, 希尔排序)
2016-06-29 22:42
741 查看
/** 包含多种静态排序方法 * Created by Andre on 2016/6/27. */ public class Sorter { /** * 快速排序 * 递归形式 * 第一个记录为枢轴 * 不稳定 * @param a 需要排序的数组 * @param low 数组的起始下标 * @param high 数组的结束下标 */ public static void QuickSort(int a[], int low, int high) { if(low >= high) return; int pivot = a[low], l = low, h = high; for(; l < h; ) { for(; l < h && a[h] >= pivot; h--); a[l] = a[h]; for(; l < h && a[l] <= pivot; l++); a[h] = a[l]; } a[l] = pivot; QuickSort(a, low, l - 1); QuickSort(a, l + 1, high); } /** * 快速排序 * 递归形式 * 第一记录为枢轴 * @param a 需要排序的数组 */ public static void QuickSort(int a[]) { QuickSort(a, 0, a.length-1); } /** * 二路归并排序 * 递归 * 稳定 * @param a 需要排序的数组 * @param low 数组的起始下标 * @param high 数组的结束下标 */ public static void MergeSort(int a[], int low, int high) { if(low >= high) return; int mid = (low + high) / 2; MergeSort(a, low, mid); MergeSort(a, mid + 1, high); int[] b = new int[high - low + 1]; int i, j, k = 0; for(i = low, j = mid + 1; i <= mid && j <= high; ){ if(a[i] < a[j]) b[k++] = a[i++]; else b[k++] = a[j++]; } while(i <= mid) b[k++] = a[i++]; while(j <= high) b[k++] = a[j++]; while(low <= high) a[high--] = b[--k]; } /** * 二路归并排序 * 递归 * @param a 需要排序的数组 */ public static void MergeSort(int a[]) { MergeSort(a, 0, a.length-1); } /** * 堆排序 * 不稳定 * @param a 需要排序的数组 */ public static void HeapSort(int[] a){ for(int i = a.length / 2; i > 0 ; i--) percDown(a, i, a.length); for(int i = a.length-1; i > 0; i--) { int tem = a[0]; a[0] = a[i]; a[i] = tem; percDown(a, 0, i); } } /** * 堆的下滤操作 * @param a 需要排序的数组 * @param i 下滤的位置 * @param n 堆的大小 */ public static void percDown(int[] a, int i, int n) { int tem = a[i]; for(int child = 2 * i + 1; child < n; i = child, child = 2 * child + 1) { if(child != n-1 && a[child] < a[child+1]) child++; if (tem < a[child]) a[i] = a[child]; else break; } a[i] = tem; } /** * 希尔排序 * 增量序列为 a.length / 2, a.length / 4, ... 1 * 不稳定 * @param a 需要排序的数组 */ public static void ShellSort(int[] a) { for(int gap = a.length / 2; gap > 0; gap /= 2) { for(int i = gap; i < a.length; i++) { int tem = a[i], j; for(j = i; j >= gap && tem < a[j - gap]; j -= gap) a[j] = a[j - gap]; a[j] = tem; } } } }
相关文章推荐
- 在命令行用 sort 进行排序
- 堆排序
- 快速排序
- 文件遍历排序函数
- 关于C#中排序函数的总结
- C#选择排序法实例分析
- C#插入法排序算法实例分析
- C#实现Datatable排序的方法
- MYSQL必知必会读书笔记第五章之排序检索数据
- SQLSERVER的排序问题结果不是想要的
- Ruby实现插入排序算法及进阶的二路插入排序代码示例
- Windows Powershell排序和分组管道结果
- C#快速排序算法实例分析
- C#通过IComparable实现ListT.sort()排序
- C#堆排序实现方法
- C#递归算法之快速排序
- C#选择法排序实例分析
- SQL学习笔记四 聚合函数、排序方法
- C#对list列表进行随机排序的方法
- jQuery拖动元素并对元素进行重新排序