Classification and implementation of sorting methods

Source: Internet
Author: User

1. Bubble sort

The principle of bubble sorting is to compare the adjacent two numbers in order to exchange them from small to large or from large to small, so that the largest or smallest number is exchanged to the last one after a trip. This comparison and exchange is then done from the beginning to the finish order.

The code is as follows:

voidBubblesort (vector<int> &unsorted) {     for(inti =0; I < unsorted.size ()-1; i++) {         for(intj =0; J < Unsorted.size ()-1; J + +) {            if(Unsorted[j] > unsorted[j +1]) {                inttemp =Unsorted[j]; UNSORTED[J]= Unsorted[j +1]; Unsorted[j+1] =temp; }        }    } }

Note that the so-called bubble, is to be adjacent to the two element comparison, if a number is the largest, it will always bubble to the top. Many of the code on the web about bubble sort is not really bubble sort, the real code is definitely unsorted[j] and unsorted[j+1] compared.

Complexity of Time: O (n2)

2. Select sort

Select Sort is to start with the first bit to iterate through the entire sequence, choosing the smallest value to place first. The same operation starts from the second and repeats the operation until the last one.

The code is as follows:

voidSelectsort (vector<int> &unsorted) {     for(inti =0; I < unsorted.size ()-1; i++) {        intMin =Unsorted[i];  for(intj = i +1; J < Unsorted.size (); J + +) {            if(Min >Unsorted[j]) {                inttemp =min; Min=Unsorted[j]; UNSORTED[J]=temp; }} Unsorted[i]=min; }}

Complexity of Time: O (n2)

3. Insert Sort

Inserting a sort is inserting a data into a sequence that is already sequenced, finding a suitable position for it, and forming a new ordered sequence. In the implementation, let's assume that the size of the sequence is 1 (which is definitely ordered), and then always insert the current element in the appropriate position.

The code is as follows:

voidInsertsort (vector<int> &unsorted) {     for(inti =1; I < unsorted.size (); i++) {        intj =i;  while(J >0&& Unsorted[j] < unsorted[j-1]) {            inttemp =Unsorted[j]; UNSORTED[J]= Unsorted[j-1]; Unsorted[j-1] =temp; J--; }    }}

Complexity of Time: O (n2)

4. Merge sort

The first way to merge a sort is to combine two ordered sequences. As long as the first number of the two series is compared, who takes the first, and then deletes the number in the corresponding sequence. Then, if the sequence is empty, then the data of the other sequence can be taken out in turn.

Knowing how to merge the two ordered sequences, we can use the divide-and-conquer method to divide a sorted array by two, two, four, until it is divided into a single number (then ordered), and then merge with the above method, culminating in the sorted array.

The code is as follows:

voidMergearray (vector<int> &unsorted,intBottomintMidinttop) {    inti = bottom, J = mid +1, M = Mid, n =top; Vector<int>Temp (unsorted.size ()); intK =0;  while(I <= m && J <=N) {if(Unsorted[i] <= unsorted[j]) temp[k++] = unsorted[i++]; Elsetemp[k++] = unsorted[j++]; }     while(i <= m) temp[k++] = unsorted[i++];  while(j <= N) temp[k++] = unsorted[j++];  for(inti =0; I < K; i++) {Unsorted[bottom+ i] =Temp[i]; }}voidMergeSort (vector<int> &unsorted,intBottominttop) {    if(Bottom <top) {        intMid = (bottom + top)/2;        MergeSort (unsorted, Bottom, mid); MergeSort (unsorted, Mid+1, top);    Mergearray (unsorted, Bottom, Mid, top); } } 

It's hard to understand at first: how to put an array "two"? See the code to understand, the use of recursive method.

Complexity of Time: O (NLOGN)

5. Quick Sort

It is also a method of divided treatment. Find the datum point, put the number smaller than the Datum point to its left, large on the right, recursion down. A specific explanation can be seen: http://developer.51cto.com/art/201403/430986.htm

The code is as follows:

voidQuickSort (vector<int> &unsorted,intFirstintLast ) {    if(First <Last ) {        inti = First/*if first + 1, consider only two of the correct number of cases, the exchange becomes wrong;*/, j =Last ; intKey =Unsorted[first];  while(I <j) { while(I < J && Unsorted[j] >=key) {J--; }             while(I < J && Unsorted[i] <=key) {i++; }            if(I <j) {inttemp =Unsorted[i]; Unsorted[i]=Unsorted[j]; UNSORTED[J]=temp; }                    }        inttemp =Unsorted[first]; Unsorted[first]=Unsorted[i]; Unsorted[i]=temp; QuickSort (unsorted, First, I-1); QuickSort (unsorted, I+1, last); }}

Why do we have to deal with J first in the loop in the code? Our benchmark is selected by the first element, and finally to the point where I and J meet, obviously the point is swapped to the left of the Datum point, so its value needs to be smaller than the datum point value. If we deal with I first, this value will be larger than the value of the Datum point, and the sort fails.

Complexity of Time: O (NLOGN)

6. Sorting Buckets

This is a way of using space to change time, the code is as follows:

voidBucketsort (vector<int> &unsorted) {    int* arr =New int[200001];//100000 to 100000     for(inti =0; I <200000; i++) {Arr[i]=0; }     for(inti =0; I < unsorted.size (); i++) {Arr[unsorted[i]+100000]++; }    intK =0;  for(inti =0; I <200000; i++) {         while(Arr[i]) {Arr[i]--; Unsorted[k+ +] = i-100000; }    }    Delete[] arr;}

This idea is used in many places.

In addition, using C + + containers to be a "bucket" would be a little better.

This article does not mention all the sorting methods, sorting methods are: Heap sorting, cardinal sort, hill sort ... Because I won't.

* * is the sorting method stable? **

This sort algorithm is stable if a sort method guarantees that the first 2 equal numbers in the sequence are the same as the pre-and post-position order of the sequences and the order of their two before and after the ordering.

Is it possible to judge whether a sorting algorithm is stable or not to understand the algorithm?

Give the result directly:

Stable: bubble sort, insert sort, merge sort, base sort

Unstable: Select Sort, quick sort (damage stability occurs at datum points and Unsorted[i], hill sort, heap sort

Classification and implementation of sorting methods

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.