An example of quicksort from the beginning of a JAVA algorithm

  • 2020-04-01 02:52:50
  • OfStack

Quicksort may sound like a fast name, but its algorithm's time complexity is at worst the same as insertion sort. The reason it's called quicksort is because it's faster on average than heap sort, and quicksort is also based on the idea of divide and conquer which is similar to merge sort, but quicksort is the original address, so you don't have to create any new storage space in the original array. The idea of quicksort is very simple. It is to select a keyword k and divide the original array into two parts, g1 and g2. All elements in g1 are smaller or equal to k, while all data in g2 are larger or equal to k. The sort method in the code is a description of the statement. The key algorithm is to find the location of k and divide the original array into two parts. The getPlocation method is the heart of quicksort. He implemented it a little bit like insertion sort just a little bit like that. Every time the end position of the element in the map as a keyword, compared with the end element array into two parts, the size and I and j is two line, between I and j number is larger than the core elements of the I and j is like a snake, when the next number is larger than the core of j j + 1, and increased the length of the I and j, and if it is smaller than the core, the I and j are going forward, and the decimal in front of the I. So if I go through this loop, I'm going to divide it by size between start and end minus 1, and then I'm going to put the core in the middle, and then I'm going to go back to where the core is.


public class QuickSort {
 public int getPlocation(int[] map,int start,int end){
  int core=map[end];
  int i=start-1;
  for(int j=start;j<=end-1;j++){
   if(map[j]<=core){
    i++;
    int cache=map[j];
    map[j]=map[i];
    map[i]=cache;
   }
  }
  i++;
  map[end]=map[i];
  map[i]=core;
  return i;
 }
 public void sort(int[] map,int start,int end){
  if(start<end){
  int p=getPlocation(map, start, end);
  sort(map, start, p-1);
  sort(map,p+1,end);
  }
 }
 public static void main(String[] args) {
  int[] map=new int[]{4,1,5,3,7,12,65,7};
  QuickSort qs=new QuickSort();
  qs.sort(map, 0, map.length-1);
  for (int i = 0; i < map.length; i++) {
   System.out.println(map[i]);
  }
 }
}


Related articles: