Quick sort, heap sort, merge sort, common better sort

Source: Internet
Author: User

1. Quick Sort

By dividing the sorted data into separate parts, one part of the data is smaller than the rest of the data, and then the two parts of the data are quickly sorted by this method. Recursive and non-recursive methods can be implemented separately. 650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/7E/D4/wKioL1cKBWiw0HXgAABgmjxck50077.png "title=" QQ picture 20160410154313.png "alt=" Wkiol1ckbwiw0hxgaabgmjxck50077.png "/>

int _quicksort (int* a,int left,int right,int key) {while (left < right) {when (left < Right&&a[left] <=a[k EY]) {left++;//Find out A[key] large subscript}while (left < right&&a[right] >=a[key]) {right--;//Find a smaller subscript a[key than}swap] (a[  Left], a[right]); Swap}if (A[left] > A[key])//If the sequence you want to sort is less than A[key] value swap (A[left],a[key]);//Key-1 when the boundary, the second time A[key] is 5 o'clock.     return left; }return key;}



650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7E/D7/wKiom1cKCRSj5rIEAAA-QBZX154723.png "title=" 20127. PNG "alt=" Wkiom1ckcrsj5rieaaa-qbzx154723.png "/>

int _quicksort2 (int* A, int left, int right, int key) {int cur = left;int prev = left-1;while (cur <= right) {if (a[cur ] (<= A[key]) {prev++;if (prev!=cur) swap (A[prev], a[cur]);} cur++;} Swap (A[prev+1],a[key]); return prev+1;}
Void quicksort (int* a, int left, int right) {assert (a);if  (left <  right) {int mid = findmid (a,left,right);//3-bit fetch, compare the left and middle numbers, find the middle number as Keyswap (a[mid],a[right ]); Int key = right;int boundary=_quicksort2 (a,left,right-1,key);//Find the boundary value after a trip sort//int  Boundary=_quicksort (A,left,right-1,key);//There are two ways to find the boundary value QuickSort (a,left,boundary-1); QuickSort (A, boundary+1,right);}}  //non-recursive borrowing stack to complete void norquciksort (int* a,int left,int right) {stack<int> s1; S1.push (left), S1.push (right);while  (!s1.empty ()) {int key = s1.top (); int _right =  s1.top (); S1.pop (); Int _left = s1.top (); S1.pop ();if  (_left >= _right)   continue;int boundary = _quicksort (a, _left, _right - 1,  key);//int boundary = _quicksort2 (A, _left, _right - 1, key); S1.push ( boundary +&NBSP;1);  //first press key to the right of the sequence S1.push (_right); S1.push (_left); S1.push (boundary-1);}} Optimized Quick Sort    three-count Int findmid (int* a, int left, int right) {Int mid  = left +  (Right - left)  / 2;if  (A[left] > a[right]) {if  (A[left] < a[mid]) return left;else if  (A[mid]>a[right]) return mid ; return right;} else{if  (A[left] > a[mid]) return left;else if  (A[mid] < a[right] ) Return mid;return right;}}


2. Heap Sequencing

The idea of heap sorting is to build the largest heap if it is sorted in ascending order, and vice versa to build the smallest heap.

After the heap is built, the first number starts and the last number is exchanged, the range of the heap is reduced (the last number is removed), and then the first number is adjusted downwards, the largest number is the last. Until there is only one number in the heap.

The process of building the heap is from the last non-leaf node until the node is adjusted downwards. Let's say we're going to sort in ascending order. That is, when the downward adjustment, the small swap to the parent node.

650) this.width=650; "src=" http://s2.51cto.com/wyfs02/M01/7E/A0/wKiom1cFwGfhLmrBAAAxn4Fa1M4828.jpg "title=" 666. JPG "alt=" wkiom1cfwgfhlmrbaaaxn4fa1m4828.jpg "/>

Void adjustdown (int *a,int size,int parent)    //downward alignment {int child =  parent * 2 + 1;           // The left child's subscript to childwhile  (child < size)         // Ensure downward alignment until child is out of range {if  (child + 1 < size&&a[child + 1] >  a[child])   //when the right child > Left child, the child changes to right children subscript {child++;} if  (A[parent] < a[child]) {swap (A[parent],a[child]);p arent = child;                child = parent *  2 + 1;       }else{break;}}} Void heapsort (int *a, int size) {assert (a);for  (int i =  (size - &NBSP;2)  / 2; i >= 0; i--) {Adjustdown (a,size,i);          //start with a non-leaf node labeled 4, and align down}for  (int i = size - 1; i  > 0; i--) {swap (a[0],a[i]);   //swaps the first and last element in the largest heap, at which point the last element is the largest adjustdown (a,i,0); Build the remaining elements to the maximum heap}}

3. Merge sort

The time complexity of the merge sort is O (NLGN) and its main idea is the Division method (divide and conquer), which divides the sequence of n elements into two sequences, then divides into 4 sequences, until each sequence has only one number, then merges two valid sequences into a valid sequence, Until the entire sequence is an ordered sequence.

Recursive implementations:

Void mergesort (int *a, int size) {assert (a);int *tmp = new int[size]; Int left = 0, right = size - 1;_mergesort (a,tmp,left,right);} Void _mergesort (int* a, int* tmp, int left, int right) {if  (left  < right) {int mid = left +  (right - left)  / 2;// Take the intermediate subscript _mergesort (a,tmp,left,mid);        //recursively _mergesort (a, tmp,  Mid+1, right);   //until recursive to the left and right sequence only one element combine (a,tmp,left,mid,mid+1,right);//2 ordered sequences merged into a memcpy (a+left , TMP, (right-left+1) *sizeof (int));//Copy the ordered sequence to the original array}}void combine (Int* a, int* tmp, int &NBSP;BEGIN1,&NBSP;INT&NBSP;END1,INT&NBSP;BEGIN2,&NBSP;INT&NBSP;END2) {int index = 0;while  (BEGIN1&NBSP;&LT;=&NBSP;END1&AMP;&AMP;BEGIN2&NBSP;&LT;=&NBSP;END2) {while  (a[begin1] <= a[begin2]&&begin1<=end1) {Tmp[index++] = a[begin1];begin1++;} while  (A[begin1] > a[begin2] && begin2 <= end2) {tmp[index++]  = a[begin2];begin2++;}} while  (BEGIN1&NBSP;&LT;=&NBSP;END1) {tmp[index++] = a[begin1++];} while  (Begin2 <= end2) {tmp[index++] = a[begin2++];}}

The recursive sort of non-recursive implementation, then take the opposite idea, the entire array is divided into n sequence, each time two series merge. Each of the two sequences is ordered, 4 sequences are combined, and so on.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/7E/D5/wKioL1cKL2rQNCyiAABamC7lFvc248.png "title=" 234234.png "alt=" Wkiol1ckl2rqncyiaabamc7lfvc248.png "/>

void MergeSort2 (int *a, int size) {assert (a); int gap = 0;int *temp = new Int[size];int count = 0;//gap refers to the difference between begin1 and end1 each time The number is, 0,1,3,7 (2^n-1) while (Gap < size) {int begin1 = 0, End1 = gap, begin2 = End1 + 1, end2 = begin2 + gap;for (; End2 &L T Size BEGIN1=END2+1,END1=BEGIN1+GAP,BEGIN2=END1+1,END2=BEGIN2+GAP) {Combine (a,temp,begin1,end1,begin2,end2); memcpy (A + Begin1,temp, (end2-begin1+1) *sizeof (int));} if (begin2 < size) {End2 = size-1; Combine (A, temp, begin1, End1, begin2, size-1); memcpy (A + begin1, temp, (end2-begin1 + 1) *sizeof (int));} Count++;gap=pow (2,count)-1;}}

Quick sort, heap sort, merge sort, common better 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.