public static <T> void quickSort(T[] items) { quickSort(items, null); } public static <T> void quickSort(T[] items, Comparator<T> comparator) { if (items == null || items.length == 0) return; quickSort(items, comparator, 0, items.length - 1); } private static <T> void quickSort(T[] items, Comparator<T> comparator, int low, int high) { // Select a pivot T pivot = items[calcPivot(low, high)]; // Move all items smaller than pivot to its left. // Move all items greater than pivot to its right. int i = low; int j = high; while (i <= j) { while (compare(comparator, items[i], pivot) < 0) i ++; while (compare(comparator, items[j], pivot) > 0) j --; if (i <= j) { swap(items, i, j); i ++; j --; } } if (low < j) quickSort(items, comparator, low, j); if (i < high) quickSort(items, comparator, i, high); } private static <T> int compare(Comparator<T> comparator, T a, T b) { if (comparator != null) return comparator.compare(a, b); else return ((Comparable)a).compareTo((Comparable)b); } private static int calcPivot(int low, int high) { return low + (high - low) / 2; } private static void swap(T[] items, int i, int j) { T temp = items[i]; items[i] = items[j]; items[j] = temp; }
Quick Sort
原创furuijie8679 博主文章分类:Interview ©著作权
©著作权归作者所有:来自51CTO博客作者furuijie8679的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
quick sort 实现
快排这个算法早就已经学过,一般直接使用STL里的sort()就可以了,粗略的想一下,貌似觉得非常的简单。就算这样,在自己具体动
qsort i++ #include 快排 -
快速排序 Quick Sort
一次划分...
数据结构与算法 快速排序 子序列 时间复杂度 -
Quick_sort快速排序
快速排序(交换排序)按照之前学过的冒泡排序,我们知道它的时间复杂度达到了O(n的2次方);那如果是对1亿个数字进行排序,则这个冒泡排序
快速排序 排序算法 算法 i++ 交换排序 -
(PAT 1101) Quick Sort (递推)
There is a cl
#include 递推 ios -
PAT 甲级 1101 Quick Sort
1101 Quick Sort (25 point(s))There is a classical process named partition in the fa
PAT甲级 Quick Sort 1101 #include c代码