One question per day 4: Quick sort

Source: Internet
Author: User

Fast sorting is the best-performing sorting algorithm at present (from the general level) with an average time complexity of O (Nlogn). The idea of fast sorting is simple, first dividing the sequence to be sorted by one element as the axis, the left element of the axis is not greater than the axis, the element on the right is not less than the axis, Next, the elements on the left side of the axis (left sub-sequence) and the right element (right sub-sequence) are divided equally (each sub-sequence does not contain an element as an axis, because it is already in the correct position), the process repeats, knowing that the number of subsequence elements is 1 o'clock, then the sort is complete. From this perspective, the fast sorting algorithm is the process of continuous Sequence division, the framework of the fast algorithm is as follows:

void qsort (int array[],int start , int  end ) { if     (start  < end ) {int  Pivot_index = partition (Array,start , 
     
      end 
     );  Qsort (Array,start , Pivot_index-        1 );     Qsort (Array,pivot_index + 1,end );  }}

There are many ways to divide (partition), in which the first element is selected as the pivot element, and then scanned from both ends of the sequence to be ordered, and when scanning from the tail to the head, if the element is greater than or equal to the pivot element, no action is required on the sequence. Because these elements are in the correct position, if an element is found to be smaller than the pivot element, then the pivot element is exchanged with the element, then the scan is stopped, the position of the scanner is saved, and if the element is less than or equal to the pivot element when it is scanned from the head to the end, no action is required on the sequence. Because these elements are also in the correct position, if an element is found to be larger than the pivot element, the interchange of the pivot element with that element is stopped, and the location of the scanner is saved. Next, check the location of the two scanners, and if the scanner intersects, the scan is complete, otherwise, repeat the scanning process starting from the current position of the scanner. Once the scan is complete, one partition is completed. The program code is as follows:

int partition (int array[],int start,int end) { int pivot = array[start];While start < end) {//start < end ensures that start does not intersect with end , otherwise//the element exchange behind is not always the correct while (  Start < end && array[end] >= pivot)--end;int temp = array[ start];array[ start] = array[end];array[ end] = temp;// start < end ensures that start does not intersect with end , otherwise the element exchange is not always correct while (start
       < end && array[start] <= pivot) + +start;int temp = array[ start];array[ start] = array[end];array[ end] = temp;} return start;}

Careful observation of the above code, in fact, two times the element exchange is not necessary, the scanning process is important is the location of the final hub element, as to where the midway pivot element is not important, because it is always changing, it is important that the value of the pivot element, Elements that need to be exchanged with the pivot element during the scan must be immediately placed in the correct position, so that when the scan is finished, the pivot element is put directly in its final position.

int partition (int array[],int start,int end) { int pivot = array[start];While start < end) {while (start < end && array[end] >= pivot)-end;array[ start] = array[end];At this time array[ start] is less than pivot, the next cycle can be started//From array[start], and forward, and array[end]//After the elements are greater than the pivot , and the value itself is shifted to//in the correct position, the value in this position is actually invalid while (start < end && array[start] <= Pivot) + +start;array[ End] = array[start];At this point, if you find an element greater than pivot in this direction, it is also//array[ start], fill array[endwith array[start]//This position is correct, as mentioned above, now//The value in this position is invalid; if no greater than P is found     Ivot element//Then,start will be equal to end, then the above assignment is invalid,//Because,start equals end, the scan is complete, the outer loop ends, this Position is filled with pivot (see the first line of code outside the loop), this//also fills the position where the value of array[endis invalid, and all//elements are in the correct position} array[  Start] = pivot;Return start;}

As you can see, a lot of unnecessary assignment operations are reduced. After the partitioning algorithm is complete, the entire fast algorithm is completed. For ease of use, a function is used to wrap up the above function:

void QuickSort(intarray[],int n){    qsort(array,01);}

Here is the test code:

int_tmain (intARGC, _tchar* argv[]) {Const intN = One;int Array[] = {7,4,8,4,4,9,2,1,-7,-5,6}; for(inti =0; i < N; ++i) {cout<<Array[i]<<"'; }cout<<endl; QuickSort (Array, N); for(inti =0; i < N; ++i) {cout<<Array[i]<<"'; }cout<<endl;return 0;}


Fast sorting can also be faster, when the dividing interval is less than the number of elements contained in a value, because the fast-track uses recursion and thus slower than the insertion sort (STL source code, this value from the 5-20 effect is similar), so an improvement is if the partition element is less than this value when the insertion sort instead of the fast row, can result in better performance. The idea of using a quick line can also find the number of K in a sequence in the O (N) time complexity (which can be the median) and the number of the first K (the number of k large is found, and the number of the top k is found). The specific idea is that when the completion of a division, no longer to two intervals to call the partition algorithm, and only in the number that contains to find the interval to use the partition algorithm, of course, when the number to find the interval is the second half interval, then first calculate the number to find in the second half of the interval should fall in which position. If in the first half of the interval, this calculation is omitted, if it is the position of pivot, then congratulations, the task is complete!

One question per day 4: Quick sort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.