The Good Programmer Java tutorial teaches you about quicksort in 5 minutes.

Quicksort is a kind of sorting algorithm that is often asked in interviews, and the average time of quicksort is relatively small compared to some other sorting algorithms.

Introduction to quicksort idea

Quicksort uses the idea of divide-and-conquer. Through a round of sorting, a sequence can be divided into two independent parts, one part of which is smaller than the base value, and the other part of which is larger than the base value. Then the sequence of the two parts is sorted according to the same algorithm until the whole sequence is in order.

The following sequence ARR is taken as an example to illustrate the basic algorithm of quicksort



The value 23 in the first position is used as the base value and is compared from the right, if ARr [high]>base,high moves forward.



Arr [high]<base,arr[low]=arr[high], then low moves back



Arr[low]<base, not swapped, low moved later

Arr[low]>base, Arr[high]= Arr[low], high forward



Arr[high]<base, Arr[low]=base, Arr[low]=base,



Low and high point to the same place,

Assign the base data to the same position as low and high point to, and the comparison ends. Then, the data before 23 and the data after 23 are compared and sorted according to the above algorithm respectively, and so on until all elements are in order.



Quicksort code implementation

Since all subsequences are sorted by the same algorithm, the recursive idea can be used to achieve quick sorting

  1. package com.qfedu.vo;
  2. public class QuickSort {
  3. public static void quickSort(int[] arr,int low,int high){
  4. int i,j,temp,t;
  5. if(low>high){
  6. return;
  7. }
  8. i=low;
  9. j=high;
  10. // Temp Specifies the number of storage benchmarks
  11. temp = arr[low];
  12. while (i<j) {
  13. // Start from the right side of the development judge, the condition is true, high decreases left
  14. while (temp<=arr[j]&&i<j) {
  15. j–;
  16. }
  17. arr[i]=arr[j];
  18. // From the left, low increases to the right
  19. while (temp>=arr[i]&&i<j) {
  20. i++;
  21. }
  22. arr[j]=arr[i];
  23. arr[i]=temp;
  24. }
  25. // Recursively calls the content on the left to sort
  26. quickSort(arr, low, j-1);
  27. // Recursively call the content on the right to sort
  28. quickSort(arr, j+1, high);
  29. }
  30. public static void main(String[] args){
  31. 15,23,7,87,34,56 int [] arr = {};
  32. quickSort(arr, 0, arr.length-1);
  33. for (int i = 0; i < arr.length; i++) {
  34. System.out.println(arr[i]);
  35. }
  36. }
  37. }

conclusion

The above is the introduction of ordinary quicksort, for quicksort, there are some improved algorithms, which can further improve the execution efficiency.