Sorting--A brief analysis of ideas (I.)

Source: Internet
Author: User

Brief introduction

This article summarizes the recent study of sorting algorithms, refining their ideas and differences. Merge sort, quick sort, heap sort, and bubble sort

Merge sort (Merging sort)
    • Merging means combining two or more ordered tables into a new, ordered table of two or more.
    • Merge sort refers to the process of decomposing unordered sequences into several ordered sub-sequences and merging ordered subsequence into a whole ordered sequence.
    • Sequences with a length of 1 are ordered.

The strategy of using 22 decomposition and merging is simple, so the merge sort is called the 2-way merge sort.

Implementation of merge sort

     Public Static void Sort(int[] arr) {if(arr = =NULL|| Arr.length = =0)return;intlen = arr.length;int[] temp =New int[Len]; MergeSort (arr,0, Len-1, temp); } Public Static void MergeSort(int[] arr,intFirstintLastint[] temp) {//Conditions        if(First < last) {intMid = (first + last)/2;            MergeSort (arr, first, Mid, temp); MergeSort (arr, Mid +1, last, temp);        Mergearray (arr, first, Mid, last, temp); }    } Public Static void Mergearray(int[] arr,intFirstintMidintLastint[] temp) {inti = First, J = mid +1;intindex = first; while(I <= mid && J <= last) {//Sorting criteria            if(Arr[i] > Arr[j]) temp[index++] = arr[i++];Elsetemp[index++] = arr[j++]; } while(I <= mid) temp[index++] = arr[i++]; while(J <= last) temp[index++] = arr[j++]; for(intK = First; K <= last;        k++) {Arr[k] = temp[k]; }    }

Another way to do this:

//will be adjacent to an ordered a[i. M] and A[M+1..N] merge to B[i. N] contains nvoidMerge (intA[],intIintMintNintB[]) {intK,j; for(k = i, j = m+1; K <= M && J <= n;k++) {if(A[i] < a[j])        {B[k] = a[i++]; }Else{B[k] = a[j++]; }    } while(i<=m) b[k++] = a[i++]; while(j<=n) b[k++] = a[j++];}//I: Hierarchy of recursion (first layer is 0)--used to indicate the specific role of A/b array in the Msort current call hierarchy://When I is odd, it is from A[s. T] Merge to B[s. T]//otherwise from b[s. T] Merge to A[s. T]voidMsort (intA[],intB[],intIintSintT) {intMif(s = = t) {if(1= = i%2) B[s] = A[s]; }Else{m = (s+t)/2; Msort (a,b,i+1, s,m); Msort (a,b,i+1, m+1, t);if(1= = i%2) Merge (A,S,M,T,B);ElseMerge (B,s,m,t,a); }}voidMergeSort (intA[],intLen) {intB[len]; Msort (A, B,0,0, len-1); Free(b);//Release Resources}

Simple analysis:
The entire merge sort process needs to be l o g n ? The recursive decomposition and merging of the layers, the algorithm of the merging sort has the time complexity ofO (N*LOGN)

Merge sort is a stable sort

Quick sorting (Quick sort)

The simplest interchange sort is a bubbling sort, and a quick sort is an improvement to the bubbling sort.

First select a keyword from the sequence to be sorted, called the pivot, by the comparison of the keyword and the pivot to divide the sequence to be ordered into two sub-sequence before and after the pivot, where all the keys of the sub-sequence before the pivot are not the pivot, the sub-sequence after the pivot is not less than the pivot, when the pivot is in place In the same way, the two sub-sequences are recursively sorted by recursion, and the whole sequence is finally ordered.

A quick sort of a division of a specific process:

    • Point the bit low to the first record of the pending record (which is also the pivot record), high points to the last record, and copies the pivot record to the point No. 0 idle unit.
    • First move the position of the high point forward until the first record that is smaller than the pivot record key is found and copied to the position indicated by PivotKey.
    • Then move the low backward to find the first record that is larger than the pivot record key and copy it to the high point.
    • Until low is equal to high, copy the pivot record to the position indicated by low
    Private Static void QSort(int[] arr) {if(arr = =NULL|| Arr.length = =0)return; QSort (arr,0, Arr.length-1); } Public Static void QSort(int[] arr,intFirstintLast) {//length greater than one        if(First < last) {intPKey = partition (arr, first, last);//Remember PKey position no longer involved, so pKey-1 and PKey + 1QSort (arr, first, PKey-1); QSort (arr, PKey +1, last); System. out. println ("key:"+ PKey); }Else{System. out. println ("First > Last"); }    } Public Static int Partition(int[] arr,intFirstintLast) {intkey = Arr[first]; while(First < last) {//Note the >= and <= here             while(First < last && Arr[last] >= key) last--; Arr[first] = Arr[last]; while(First < last && Arr[first] <= key) first++;        Arr[last] = Arr[first]; } Arr[first] = key;returnFirst }

To avoid the maximum or minimum pivot keyword, you can use the "three-in-the-middle" method, that is, the a[s], a[t], a[(s+t)/2] Three keywords in the size of the center of the record as a pivot, and A[s] Interchange

Basic operations of heap sequencing heap

Heap is a kind of complete binary tree, if all the non-leaf nodes in the heap are not greater than the left and right children, it is called the small top heap; if all non-leaf nodes in the heap are not less than their left and right children, it is called the large top heap

Structure type of the heap

typedef struct{int*RCD;//heap base, number No. 0 I hope not.    intN//Heap length    intSize//Heap container    intTag//Small top pile and big Top pile logo    int(*prior) (intAintb);//function variables for keyword precedence comparisons} Heap;intGreatprior (intXintY) {returnx>=y; }intLessprior (intXintY) {returnx<=y; }
    • Screening
      • A heap filtering operation that maintains the heap characteristics of a subtree that is the root of a specified POS node in the heap, provided that the left and right subtrees of the POS node satisfy the heap characteristics
      • Process: The POS node is compared with the priority of the left and right children, if POS node priority is finished; otherwise POS node and left and right child priority exchange position, POS position is shifted down, repeat the above steps.
intSwapheapelem (Heap &h,intIintj) {if(I <0|| I > H.N | | J <0|| J > H.N)return 0;intT    t = H.rcd[i];    H.rcd[i] = H.rcd[j]; H.RCD[J] = t;return 1;} Heap, the filter operation on the heap, the specifiedPOSnode is the root of the subtree for the maintenance of the properties of the heap, the premise isPOSThe left and right sub-trees of the nodes satisfy the heap characteristics void Shiftdown (heap &h,int POS){intc, RC; while(POS<=h.n/2) {c =POS * *; rc =POS * *+1;if(RC&LT;=H.N && H.prior (H.rcd[rc],h.rcd[c])) c = RC;//Note here the position of the comparison element of the functionif(H.prior (h.rcd[POS],H.RCD[C]))return; Swapheapelem (H,POS, c);POS= C; }}
    • Delete Heap top node
      • Process: 1, remove the top node of the heap, 2, the heap top node and the heap node exchange position, and the heap length minus 1, 3, the top node of the heap screening
intint &e){    if(H.n<=0return0;    e = H.rcd[1];    SwapHeapElem(H,1,H.n);    if(H.n>1)  ShiftDown(H,1);    return1
    • Build heap Operations
void MakeHeap(Heap &H,int a[],int n,intsize,int tag,int (*prior)(int a,int b)){    H.rcd = a;    H.n = n;    H.sizesize;    H.tag = tag;    H.prior = prior;    int i;    // 叶子结点满足堆特性,故不需要筛选     for( i = H.n/20; i -- ){        ShiftDown(H,i);    }}
Heap sort (heap sort)
    • The large top heap can be sorted in ascending order using the characteristics of the heap, and the small top heap can be sorted in descending order. First, the ordered sequence is built into a large top pile, which makes the top node of the heap the largest, the heap top node and the heap tail exchange position, the heap length minus 1, the remainder node is adjusted to the heap, and the secondary large value node is obtained. Repeat this process to get an ascending sequence
void HeapSort(int a[],int n){    Heap H;    MakeHeap(H,a,n,n+2,1,lessPrior);    int e;    forint0; i -- ){        if(RemoveFirsHeap(H,e) )            printf("%d ",e);    }}
Bubble sort (Bubble sort)
    • During the first bubbling process, first and second records are compared, and if reversed, the position is swapped. Then in comparing the second and third records, proceed sequentially until the n-1 and nth records are compared, at which point the nth record is the largest. The second trip bubbles the larger record to the n-1 position until all the records are in order.
void BubbleSort(intintlen){    int t;    int i, j;    // i表示已经排序的个数    for( i = 0len; i ++ ){        // 开始冒泡到len-i,len-i之后表示已经达到最值        for( j = 1len-i; j ++ ){            if( a[j-1] < a[j] ){                t = a[j-1];                a[j-1] = a[j];                a[j] = t;            }        }    

Improved:

void Bubblesort (intA[],int Len){intTintI, J, Flag; Flag =-1;//I indicates the number of rows that have been ordered, (and the number of rows to the end)    //flag indicates a[flag-1,flag. LEN-1] has been ordered sequentially, so no reordering sequence after flag     for(i =0; I <Len; i + +) {if(Flag! =-1) {i =Len-Flag;//Indicates the number of rows that have been orderedFlag =-1; } for(j =1; J <Len-I.; J + +) {if(A[j-1] > A[j]) {flag = J; t = a[j-1]; A[j-1] = A[j];            A[J] = t; }        }    }}

Three implementations of other learning link bubbling sorts

Sorting--A brief analysis of ideas (I.)

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.