Algorithm Introduction Learning Linear time sequencing + sequencing algorithm stability end

Source: Internet
Author: User

Before we learn several sorting algorithms are based on the comparison, for any input data they are applicable, its worst time complexity will not be less than NLGN;
But for some more special input data, we can sort it by other methods instead of comparing it to achieve linear time complexity. Here are three of these algorithms: counting sort, cardinal sort, bucket sort (because these algorithms are not common, I only implement the Count sort, the other two sorts are represented by pseudo code).

I. Counting sort
Algorithm idea: Given n the number between 0–k (K is a not too large integer), we can count how many are smaller than the number in front of each number, then we can directly determine the position of the number in the array, for example, there are 17 numbers in front of X, then x should be placed in position 18th, Of course, if there are multiple identical elements we don't need to put them all in one place and need to make some changes. Complexity of Time: O (n+k)
The code is as follows:

#include <iostream>#include <cstdio>#include <cstring>usingnamespace Std;#Define MAXN 10000///The   count sort is not sorted by comparison, so the efficiency is higher///   but only a small range of positive integers can be sortedvoidCountingsort (int*a,intN) {  ///Count Sort: Sort the n number between 0--k        intk=0; for(intI=1; i<=n;i++) K=max (K,a[i]);intC[MAXN],B[MAXN];//  C used to record intermediate results, B to record sorting resultsMemset (c,0,sizeof(c)); for(intI=1; i<=n;i++) c[a[i]]++;///   Statistics a[i] number of occurrences        / * Previously I used the following way to count sort int cnt=0;                         for (int i=0;i<=k;i++) while (C[i]] {b[cnt++]=i;                    c[i]--;        This can also get results, but this is actually an unstable sort method. */         for(intI=1; i<=k;i++) c[i]=c[i]+c[i-1];///   statistics not less than the number of I         for(inti=n;i>=1; i--)///   forward from the back to make the sequencing stable{B[c[a[i]]]=a[i];///   in a[i] location record a[i];c[a[i]]--;///   If there are multiple identical element x, we reduce the value of c[x] by 1 per} for(intI=1; i<=n;i++) A[i]=b[i];///   Copy the sorted result back to the original array}intMain () {intn=5, a[Ten]; cout<<"Please enter"<<n<<"Number:"<<endl; for(intI=1; i<=n;i++) cin>>a[i];      Countingsort (A,n); cout<<"sorted array after:"<<endl; for(intI=1; i<=n;i++) cout<<a[i]<<" "; cout<<endl;return 0;}

Two. Base sorting
Algorithm idea: The base order is actually the number of n bits to sort, each number of each bit needs to be considered. According to our general idea, we should sort by the highest bit first, then the next high order .... But the idea of a cardinal sort, in contrast, is to sort by the lowest bit first, and then follow the second bit .... The last is the highest, and of course we need to choose an appropriate algorithm for each bitwise ordering.
The pseudo code is as follows:

RadixSort(A,d)   for(int i=1;i<=d)       doasorttosorton digit it

Three. Sorting buckets
The bucket sort handles the case where the input elements fall evenly between the [0,1] intervals. The idea is to divide the interval [0,1] into n equal-sized intervals, or buckets, and then sort the elements within each bucket, and then you can output them directly. Because the input is uniform, the distribution of these elements in these buckets should also be relatively uniform, there will not be many elements fall in a bucket, so there is a higher efficiency.
We use the chain list to implement, for the element A[i], we put it in the bucket numbered floor (na[i]), the inner order of the barrel we can use the insertion sort.
The pseudo code of the algorithm is as follows:

BucketSort(A){    n = length[A];    for(int i=1;i<=n;i++)        do insert A[i] into list B[floor(nA[i])]    for(int i=0;i<n;i++)        do sort list B[i] with insertion sort     concatenta the lists B[0],B[1],...,B[n-1]   in order}

Four. Stability termination of various sorting algorithms
Why should we put forward the concept of stability? Because in practice we typically sort a set of records by a key value in the record, such as a group of records that contain height, weight, and age of three, and then we need to sort them by age. At this point we hope that if the key values are equal, the data entered first should be in the front instead of the random rows. So the sort algorithms that we learned before are stable, and those are unstable?
Let's first give a general conclusion, and then we'll briefly explain it in turn:
The stable sorting algorithms are: Insert sort, merge sort, count sort, base sort.
The unstable sorting algorithms are: heap sort, quick sort.

1. Insert Sort
For the insertion sort, the same element is always in front of the inserted one, so it must be stable.

2. Merge sort
For the merge sort, we focus on the merging process, and when we make sure that the two elements are the same size in the comparison, we can make sure that the algorithm is stable by putting the coordinates small in front.

3. Heap Sequencing
Whether it is the process of building heap or heap sequencing is the process of continuous adjustment, consider node I, and i+1 have the same child nodes, and then a certain time when the node i+1 the child nodes are adjusted up and I the child nodes are not adjusted; This situation indicates that the heap ordering is not stable.

4. Quick Sort
In the case of a split, there is an unstable situation in which the key element is switched to the middle, causing it to be disrupted by the relative order of the elements in the back, so the fast line is unstable.

5. Counting sort
The count sort finally determines the position of each number, is determined from the backward, so the same elements can be guaranteed, the original after the sorting is still behind; so the counting sort is stable.

6. Base sorting
It is also stable if the cardinality sort is chosen as a stable sorting method when ordered by each one.

Algorithm Introduction Learning Linear time sequencing + sequencing algorithm stability end

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.