Quick sort (quick sort learning system)

Quick sort is actually using a divide and conquer idea that find a number p in the original array, and then the original array number than the number p into the right side of this large number, the ratio of the number of small p, into the left side of the number.

Formulas: 1. To find the fast axis 2. The left row 3. The right of the fast row

Subject code as follows:

void quick_sort(int * data,int left,int right){
  if(left < right){
    int* index = partition(data,left,right);
    quick_sort(data,left,index[0]-1);
    quick_sort(data,index[1]+1,right);
  }
}

Quick sort, the most important thing is to write the partition partition function, there are three methods to achieve:

1. unidirectional scanning zoning laws

code show as below:

int partition(int * data,int left,int right){
  int piovet = left,scanner = left+1,bigger = right;
  while(scanner <= bigger){
    if(data[scanner] <= data[piovet])
      scanner++;
    else{
      swap(data,bigger,scanner); 
      bigger--;
    }
  }
  swap(data,bigger,piovet); 
  return bigger;
}

2. The bi-directional scanning zoning

 The idea is bidirectional scanning, the scanning head and tail pointers to the middle, left to find the elements of the main element is greater than, less than or equal to find the right element of the main element, the two switching, scanning continues until no major elements left, right small no element.

code show as below:

int partition(int * data,int left,int right){
  int piovet = left,smaller = left+1,bigger = right;
  while(bigger >= smaller){
    while(data[smaller] <= data[piovet]&& smaller <= bigger) smaller++;
    while(data[bigger] > data[piovet] && smaller <= bigger) bigger--;
    if(smaller < bigger){
      swap(data,smaller,bigger); 
    }
  }
  swap(data,bigger,piovet); 
  return bigger;
}

3. The three-hand partition law - when the same element, can improve the efficiency of

code show as below:

int* partition(int * data,int left,int right){
  int val[2] = {0};
  int equal = left,scanner = left+1,bigger = right;
  while(bigger >= scanner){
    if(data[scanner] < data[equal]){
      swap(data,scanner,equal);
      scanner++;
      equal++;
    }else if(data[scanner] == data[equal]){
      scanner++;
    }else{
      swap(data,scanner,bigger);
      bigger--;
    }
  }
  val[0] = equal;
  val[1] = bigger;
  return val;
}

Guess you like

Origin www.cnblogs.com/Alice-Fourier/p/12364855.html