Quick Sort

妖狐艹你老母 2022-01-16 12:39 311阅读 0赞
  1. public static <T> void quickSort(T[] items)
  2. {
  3. quickSort(items, null);
  4. }
  5. public static <T> void quickSort(T[] items, Comparator<T> comparator)
  6. {
  7. if (items == null || items.length == 0)
  8. return;
  9. quickSort(items, comparator, 0, items.length - 1);
  10. }
  11. private static <T> void quickSort(T[] items, Comparator<T> comparator, int low, int high)
  12. {
  13. // Select a pivot
  14. T pivot = items[calcPivot(low, high)];
  15. // Move all items smaller than pivot to its left.
  16. // Move all items greater than pivot to its right.
  17. int i = low;
  18. int j = high;
  19. while (i <= j)
  20. {
  21. while (compare(comparator, items[i], pivot) < 0)
  22. i ++;
  23. while (compare(comparator, items[j], pivot) > 0)
  24. j --;
  25. if (i <= j)
  26. {
  27. swap(items, i, j);
  28. i ++;
  29. j --;
  30. }
  31. }
  32. if (low < j)
  33. quickSort(items, comparator, low, j);
  34. if (i < high)
  35. quickSort(items, comparator, i, high);
  36. }
  37. private static <T> int compare(Comparator<T> comparator, T a, T b)
  38. {
  39. if (comparator != null)
  40. return comparator.compare(a, b);
  41. else
  42. return ((Comparable)a).compareTo((Comparable)b);
  43. }
  44. private static int calcPivot(int low, int high)
  45. {
  46. return low + (high - low) / 2;
  47. }
  48. private static void swap(T[] items, int i, int j)
  49. {
  50. T temp = items[i];
  51. items[i] = items[j];
  52. items[j] = temp;
  53. }

转载于:https://blog.51cto.com/7371901/1604124

发表评论

表情:
评论列表 (有 0 条评论,311人围观)

还没有评论,来说两句吧...

相关阅读

    相关 quick_sort

    于冒泡排序是以相邻元素来比较和交换的,因此,若一个元素离其最终位置较远,则需要进行多次的比较和移动操作。而快速排序则很好的解决了上述问题。 所以,可以说快排是冒泡排序的...

    相关 快速排序(Quick Sort)

    一、算法原理 设要排序的数组是A\[0\]……A\[N-1\],首先任意选取一个数据(通常选用数组的第一个数)作为关键 数据,然后将所有比它小的数据放到它前面,所有比它大

    相关 快速排序(Quick Sort)

    快速排序可以理解为:快速排序=挖坑填数+分治算法; 快速排序(Quick Sort)使用分治法(Divide and conquer)策略来把一个序列分为两个子序列,左右两个

    相关 快速排序(Quick-Sort)

    快速排序的主要思想是根据一个基准数(一般是待排序集中第一个元素)将一个待排序集分成左右两部分,其中左半部分数据集比右半部分数据集均要小或大,接下来,对左和右半部分按照相同的方法

    相关 快速排序(quick sort)

    快速排序是由东尼·霍尔所发展的一种排序算法。在平均状况下,排序n个项目要Ο(n log n)次比较。在最坏状况下则需要Ο(n2)次比较,但这种状况并不常见。事实上,快速排序通常