[Sort] About eight sorting algorithms and their characteristics are summarized

Overview:

    Eight sorting algorithms are typically used: insertion sort, selection sort, bubble sort, Shell sort, merge sort, quick sort, heap sort, radix sort, each method has its appropriate usage scenario, data may be selected according to the specific .

    Several concepts:

    Internal sorting: Sort element during sorting all stored in memory;

    External sorting: Sort not all of the elements during storage, must be based on the requirements during the sorting process in memory constantly moving between the inner and sorted storage;

    (In addition to the eight sorting algorithm merge sort is an external multi-channel ordering, all other internal sorting)

    Stability: refers after sorting, the same element value of the original holding position in the sequence is relatively invariant.

    Each time the algorithm complexity, spatial complexity, and the auxiliary space required stability as follows:

 

Implementation (here are from small to large sort):

1. bubble sort:

The idea is simple bubble sort, that is, each index i, j take traversed from 0 to n-1-i (n is the length of the array), if the two adjacent elements of s [j]> s [j + 1], exchanged, so that every time the largest element has moved to the right rear position.

void bubbleSort(vector<int> &s){
    for (int i = 0; i < s.size(); i++){
        for (int j = 0; j < s.size() - 1 - i; j++){
            if (s[j] > s[j + 1])  swap(s[j], s[j + 1]);
        }
    }
}

Bubble sort characteristics: stability, after each sorting, the latter element is certainly already sorted, it may be determined each time after a sorting element in its final position, the number of comparisons bubble sort: n (n- 1) / 2, the number of movements: 3n (n-1) / 2.

2. Insert Sort:

Insertion sort divided into simple insertion sort and binary insertion sort; simple insertion sort thought per trip ordering elements inserted into the already been booked array sequence, the binary insertion sort is improved insertion sort, since the front half portion is already sorted. number of columns, so we do not turn in order to find the insertion point, binary search methods can be used to accelerate the speed to find the insertion point.

Simple insertion sort:

void insertSort(vector<int> &s){
    if (s.size() > 1){
        for (int i = 1; i < s.size(); i++){
            for (int j = i; j > 0 && s[j] < s[j - 1]; j--){
                swap(s[j], s[j - 1]);
            }
        }
    }
}

Binary insertion sort:

void binaryInsertSort (Vector < int > & S) {
     int Low, High, m, TEMP, I, J;
     for (I = . 1 ; I <s.size (); I ++ ) {
         // using binary search process should find inserted location 
        Low = 0 ; 
        High = I - . 1 ;
         the while (Low <= High) { 
            m = (Low + High) / 2 ;
             IF (S [m]> S [I]) High = m - . 1 ;
             the else   = m + Low . 1 ; 
        } 
        // unified mobile element, the element is inserted in the correct position
        temp = s[i];
        for (j = i; j > high + 1; j--){
            s[j] = s[j - 1];
        }
        s[high + 1] = temp;
    }
}

Insertion sort characteristics: stability, the worst case comparison n * (n-1) / 2 times, the situation is more preferably n-1 times

3. choose Sort:

Selection Sort idea is to select the minimum and that s [i] from the rear of the element i for each index i exchanged.

void selectSort(vector<int> &s){
    if(s.size()>1){
        for(int i=0;i<s.size();i++){
            int min=i;
            for(int j=i+1;j<s.size();j++){
                if(s[j]<s[min])  min=j;
            }
            swap(s[i], s[min]);
        }
    }
}

Select the sort of characteristics: instability, per trip after ordering the preceding element certainly has been sorted, the sorting can be determined after each element will be in its final position.

4. Quick Sort:

Quicksort is a better average performance of the sort sort idea is to select a data (usually the first array number) per trip as sort key data, then it is smaller than the number of all are placed in the left of it All numbers are bigger than it put it right.

void quickSort(vector<int> &s, int low, int high){
    if (low >= high)  return;
    int l = low, r = high, val = s[low];
    while (l < r){
        while (l < r&&s[r] >= val)  r--;
        if (l < r)  s[l++] = s[r];
        while (l < r&&s[l] <= val)  l++;
        if (l < r)  s[r--] = s[l];
    }
    s[l] = val;
    quickSort(s, low, l - 1);
    quickSort(s, r + 1, high);
}

Quick sort features:

1. unstable;
2. quicksort process does not produce an ordered sequence, but each has a trip element on the ordering its final position;
3. value of each selection key array can be divided into two when the sub-array, fast sort algorithm fastest, when the array is already positive sequence or reverse slowest;
4. recursion independent of the processing order of the partitions obtained after each division;
5. the n keywords quicksort, the maximum depth of recursion is n, the minimum depth of recursion log2n;

The above quick sort algorithm is a recursive algorithm, non-recursive algorithms use stack to achieve:

//进行区域的划分
int partition(vector<int> &s, int low, int height){
    int val = s[low];
    while (low < height){
        while (low < height&&s[height] >= val)
            height--;
        s[low] = s[height];
        while (low < height&&s[low] <= val)
            low++;
        s[height] = s[low];
    }
    s[low] = val;
    return low;
}
//排序
void quickSortNonRecursive(vector<int> &s, int low, int height){
    stack<int> p;
    if (low < height){
        int mid = partition(s, low, height);
        if (mid - 1 > low){
            p.push(low);
            p.push(mid - 1);
        }
        if (mid + 1 < height){
            p.push(mid + 1);
            p.push(height);
        }
        while (!p.empty()){
            int qHeight = p.top();
            p.pop();
            int pLow = p.top();
            p.pop();
            int pqMid = partition(s, pLow, qHeight);
            if (pqMid - 1 > pLow){
                p.push(pLow);
                p.push(pqMid - 1);
            }
            if (pqMid + 1 < qHeight){
                p.push(pqMid + 1);
                p.push(qHeight);
            }
        }
    }
}

5. Hill Sort:

Shell sort insertion sort is based on a species sorting algorithm , thought is an array of length n s, h intervals per trip sorted into groups based on each set of data insertion sort method sorts, and then decreases the value of h , so that the beginning of the packet, although more time, but each set of data is small, h is reduced but basically ordered plurality of data each, and the insertion sort already ordered array of substantially higher efficiency of sorting.

void shellSort(vector<int> &s){
    int n = s.size(), h = 1;
    while (h < n / 3)  h = 3 * h + 1;
    while (h >= 1){
        for (int i = h; i < n; i++){
            for (int j = i; j >= h && s[j] < s[j - h]; j -= h){
                swap(s[j], s[j - h]);
            }
        }
        h /= 3;
    }
}

Hill sorting features: instability, after each sort we can not guarantee there is an element in the final position

6. merge sort:

The idea is to merge sort two ordered tables merged into a new ordered list, i.e. the sequence to be sorted into a number of subsequences, each subsequence is ordered. And then ordered the whole sub-sequences into an ordered sequence. That is first divided into two parts, and finally merge.

 

const int maxn=500000,INF=0x3f3f3f3f;
int L[maxn/2+2],R[maxn/2+2];
void merge(vector<int> &a,int n,int left,int mid,int right){
    int n1=mid-left,n2=right-mid;
    for(int i=0;i<n1;i++)  L[i]=a[left+i];
    for(int i=0;i<n2;i++)  R[i]=a[mid+i];
    L[n1]=R[n2]=INF;
    int i=0,j=0;
    for(int k=left;k<right;k++){
        if(L[i]<=R[j])  a[k]=L[i++];
        else  a[k]=R[j++];
    }
}
void mergesort(vector<int> &a,int n,int left,int right){
    if(left+1<right){
        int mid=(left+right)/2;
        mergesort(a,n,left,mid);
        mergesort(a,n,mid,right);
        merge(a,n,left,mid,right);
    }
}

 

Merge sort characteristics: stability, may be used in sequential storage structure and chain store, the time complexity in the best and worst case is O (nlogn)

7 heap sort:

Heap sort is a sorting algorithm based selection sort, heap is approximately a complete binary tree structure, and the key or index satisfies a child node is always less than (or greater than) its parent node. Maximum stack mode used here: the maximum value of the elements are always located in the top of the stack of the whole tree, than the value of the parent node of each child node is small, to keep such a stack structure, so once inside the heap data changes, To Construction of the heap once again.

void max_heapify (Vector < int > & ARR, int Start, int End) {
     // build parent index and the child node index 
    int DAD = Start;
     int Son = DAD * 2 + . 1 ;
     the while (Son <= End) { // if the child node index in the range of only compared 
        IF (son + . 1 <= End && ARR [son] <ARR [son + . 1 ]) // first compares two child nodes size, select the maximum 
            son ++ ;
         IF (ARR [DAD]> ARR [son]) // If the child node representing the parent node is greater than the adjustment is completed, directly out function 
            return ;
         the else {// Otherwise exchange Sons content was continued child nodes and grandchild nodes comparing 
            the swap (ARR [DAD], ARR [Son]); 
            DAD = Son; 
            Son = DAD * 2 + . 1 ; 
        } 
    } 
} 

void heap_sort (Vector < int > & ARR , int len) {
     // initialization, i began to adjust from the last parent node 
    for ( int I = len / 2 - . 1 ; I> = 0 ; i-- ) 
        max_heapify (ARR, i, len - . 1 );
     // first row of the first element and has done a good exchange before the elements, and then re-adjust (the element immediately before the adjustment element), until sorted
    for (int i = len - 1; i > 0; i--) {
        swap(arr[0], arr[i]);
        max_heapify(arr, 0, i - 1);
    }
}

HEAPSORT Features: instability, the worst, the best, the average time complexity are O (nlogn)

8. Radix Sort:

Radix sort is a non-comparative type integer sorting algorithm, the principle is to cut the number of bits of data according to different numbers, and each median comparison, similar to the one million telephone numbers sort of problem, radix sort using high efficiency

// Find the number of bits in the array the maximum number as radix sorting cycles 
int KeySize (Vector < int > & S, int n-) {
     int Key = . 1 ;
     for ( int I = 0 ; I <n-; I ++ ) {
         int TEMP = . 1 ;
         int R & lt = 10 ;
         the while (S [I] / R & lt> 0 ) { 
            TEMP ++ ; 
            R & lt * = 10 ; 
        } 
        Key = (TEMP> Key)? TEMP: Key; 
    } 
    return key;
}

//基数排序
void RadixSort(vector<int> &s, int n){
    int key = KeySize(s, n);
    int bucket[10][10] = { 0 };
    int order[10] = { 0 };
    for (int r = 1; key > 0; key--, r *= 10){
        for (int i = 0; i < n; i++){
            int lsd = (s[i] / r) % 10;
            bucket[lsd][order[lsd]++] = s[i];
        }
        int k = 0;
        for (int i = 0; i < 10; i++){
            if (order[i] != 0){
                for (int j = 0; j < order[i]; j++)
                    s[k++] = bucket[i][j];
            }
            order[i] = 0;
        }
    }
}

Radix sort characteristics: stability, the time complexity is O (nlog (r) m), where r is the radix taken, and m is the number of stacks, at some point, radix sorting method efficient than other sort of stability law.

 

Part Reference: Baidu Encyclopedia, micro-channel public number five minutes learning algorithm original article, " This is probably the best in the Eastern Hemisphere analysis of the top ten ranking algorithm article " -  https://mp.weixin.qq.com/s/Qf416rfT4pwURpW3aDHuCg

 

Guess you like

Origin www.cnblogs.com/nibolyoung/p/10954744.html