快速排序

要求算法实现二背下来

时间复杂度:O(nlogn)

  1. 快排的性能
    快排在排序算法中性能最好,数据越大排序最优,但在最坏的极端情况下会退化成O(n²)。若前提已知待处理的数据会出现极端的情况下,可以选择比较稳定的归并排序。
    最坏的情况:每次所取的基准都是最小的

算法实现:

  1. public void test(){
  2. int n[] = { 6, 5, 2, 7, 3, 9, 8, 4, 10, 1 };
  3. //记得传入右边边界要减一
  4. sort(n,0,n.length-1);
  5. for (int m : n) {
  6. System.out.println(m+"\t");
  7. }
  8. }
  9. public void sort(int[] n,int left,int right){
  10. //制定递归出口
  11. if (left<right) {
  12. int index = quicksort(n, left, right);
  13. //确定好下标,为第二次递归做准备
  14. sort(n, left, index - 1);
  15. sort(n, index + 1, right);
  16. }
  17. }
  18. public int quicksort(int[] n,int left,int right){
  19. //将随机一个数与最左边的一个数交换
  20. swap(n,new Random().nextInt(right-left+1)+left,left);
  21. int temp = n[left];
  22. int tempIndex = left;
  23. while (right>left){
  24. while (temp<=n[right] && right>left){
  25. right--;
  26. }
  27. while (temp>=n[left] && right>left){
  28. left++;
  29. }
  30. //该交换为将大于基数的数移至基数左边
  31. //小于基数的数移至基数右边
  32. swap(n,left,right);
  33. }
  34. //该交换为基准与确定好的位置交换
  35. swap(n,tempIndex,left);
  36. //回传的是确定好位置的基准元素下标
  37. return left;
  38. }
  39. public void swap(int[] n,int i,int j){
  40. int temp = n[i];
  41. n[i] = n[j];
  42. n[j] = temp;
  43. }

写法二:

  1. public class QuickSort {
  2. private int[] array;
  3. public QuickSort(int[] array) {
  4. this.array = array;
  5. }
  6. public void sort() {
  7. quickSort(array, 0, array.length - 1);
  8. }
  9. public void print() {
  10. for (int i = 0; i < array.length; i++) {
  11. System.out.println(array[i]);
  12. }
  13. }
  14. /**
  15. * 递归排序
  16. * @param src
  17. * @param begin
  18. * @param end
  19. */
  20. private void quickSort(int[] src, int begin, int end) {
  21. if (begin < end) {
  22. int key = src[begin];
  23. int i = begin;
  24. int j = end;
  25. while (i < j) {
  26. while (i < j && src[j] > key) {
  27. j--;
  28. }
  29. if (i < j) {
  30. src[i] = src[j];
  31. i++;
  32. }
  33. while (i < j && src[i] < key) {
  34. i++;
  35. }
  36. if (i < j) {
  37. src[j] = src[i];
  38. j--;
  39. }
  40. }
  41. src[i] = key;
  42. quickSort(src, begin, i - 1);
  43. quickSort(src, i + 1, end);
  44. }
  45. }
  46. }