一.代码

  1. public class QuickSort {
  2. public static void quickSort(int[] arr, int startIndex, int endIndex) {
  3. if (startIndex >= endIndex) {
  4. return;
  5. }
  6. int pivotIndex = partition(arr, startIndex, endIndex);
  7. quickSort(arr, startIndex, pivotIndex - 1);
  8. quickSort(arr, pivotIndex + 1, endIndex);
  9. }
  10. private static int partition(int[] arr, int startIndex, int endIndex) {
  11. int pivot = arr[startIndex];
  12. int left = startIndex;
  13. int right = endIndex;
  14. while (left != right) {
  15. while (left < right && arr[right] >= pivot) {
  16. right--;
  17. }
  18. while (left < right && arr[left] <= pivot) {
  19. left++;
  20. }
  21. if (left < right) {
  22. int temp = arr[left];
  23. arr[left] = arr[right];
  24. arr[right] = temp;
  25. }
  26. }
  27. arr[startIndex] = arr[left];
  28. arr[left] = pivot;
  29. return left;
  30. }
  31. }

二.稳定性

不稳定。5 3 4 3 6 7 10 排序 3 3 4 5 6 7 10 ,3的顺序变了。

三.时间复杂度

最优O(nlogn) 最差O(n^2) 平均O(nlogn)