Summary of 10 sorting algorithms

Source: Internet
Author: User
Tags pow

There are many sorting algorithms, so it is important to use which algorithm in a particular scenario. In order to select the appropriate algorithm, the following criteria can be considered in the recommended order:

(1) Execution time
(2) Storage space
(3) Programming work
For the case of small Data volume, (1) (2) The difference is not small, the main consideration (3), and for the large amount of data, (1) is the first.

The main sorting methods are:
First, Bubble (Bubble) sort--adjacent exchange
Second, choose the sort--each time min/big row in the corresponding position
Insert sort-Inserts the next row in the sorted sequence
Shell (shell) sort--Reduce increment
Five, merge sort
Six, quick sort
Vii. sequencing of Heaps
Eight, topological sort
Nine, tournament ranking
Ten, the base sort



First, Bubble (Bubble) sort

void Bubblesortarray () {for       (int. i=1;i<n;i++)       {for         (int j=0;i<n-i;j++)          {               if (a[j]>a[j+ 1]//Compare interchange adjacent element                {                    int temp;                    TEMP=A[J];
          
a[j+1]=temp; } }

Efficiency O (n²), suitable for sorting small lists.


Second, choose the sort

void Selectsortarray () {     int min_index;     for (int i=0;i<n-1;i++)     {          min_index=i;          for (int j=i+1;j<n;j++)//Select the smallest item per scan             
Min_index=j; if (min_index!=i)//Find the minimum item interchange, move this item to the correct position in the list { int temp; Temp=arr[i];
       Arr[i]=arr[min_index];
       Arr[min_index]=temp; }    } }


Efficiency O (n²), suitable for lists with small sorting.


Third, insert sort

void Insertsortarray () {for     (int i=1;i<n;i++)//loop starts with the second array element because Arr[0] is the first sorted part     {         int temp=arr[i];// Temp is marked as unsorted first element         int j=i-1;         while (j>=0 && arr[j]>temp)/* Compares the temp to the sorted element from small to large, looking for where temp should be inserted */         {             arr[j+1]=arr[j];             j--;         }         Arr[j+1]=temp;     

Optimal efficiency o (n); the worst Efficiency O (n²) is the same as bubbling, selection, suitable for sorting a small list
If the list is basically ordered, the insertion sort is more efficient than bubbling and selecting.


Shell (shell) sort--Reduce the incremental sort

void Shellsortarray () {     for (int incr=3;incr<0;incr--)//increment decrement, increment 3,2,1 For example     {for         (int l=0; l< (n-1)/incr; l++)//Repeat the partitioning of each sub-list         {for             (int i=l+incr;i<n;i+=incr)//Apply Insert sort             {                 int temp=arr[i] to each sub-list;                 int j=i-incr;                 while (j>=0&&arr[j]>temp)                 {                     arr[j+incr]=arr[j];                     J-=INCR;                 }                 arr[j+incr]=temp;             }         }     

Applies to sorting a small list.
The efficiency estimate O (nlog2^n) ~o (n^1.5), depends on the initial size of the increment value. It is recommended that prime numbers be used as increment values, because if the increment value is a power of 2, the same element will be compared again in the next channel.
Shell (shell) sorting improves the insertion sort and reduces the number of comparisons. is an unstable sort, because elements in the sort process may jump back and forth.


Five, merge sort

void mergesort (int low,int high) {     if (low>=high)   return;//stop     else int mid= (Low+high) when there is one element left in each child list/2;/ * Divide the list into equal two sub-lists, if there is an odd number of elements, the left child list is greater than the right sub-list *     /mergesort (LOW,MID);//Sub-list further divides     mergesort (mid+1,high);     int [] B=new int [high-low+1];//creates an array to hold the merged elements for     (int i=low,j=mid+1,k=low;i<=mid && j<=high;k++) /* Two sub-lists are sorted and merged until one end of the two sub-lists     *         /{if (Arr[i]<=arr[j];)         {             b[k]=arr[i];             i++;         }         else        {b[k]=arr[j]; j + +;}     }     for (   ; j<=high;j++,k++)//If there are still elements in the second sub-list, append to the new list         b[k]=arr[j];     for (   ; i<=mid;i++,k++)//If there are still elements in the first sub-list, append to the new list         b[k]=arr[i];     for (int z=0;z

Efficiency O (NLOGN), there is no difference between the best, average, and worst use case efficiency of the merge.
Suitable for sorting large lists, based on divide-and-conquer method.

Six, quick sort

/* Fast sorting algorithm idea: Select a pivot element, treat the sorting sequence to split, after the division of the sequence of a part less than the pivot element, a part larger than the pivot element, and then the two well-divided sub-sequence of the above process. *                 /void swap (int a,int b) {int t;t =a; a =b; b =t;} int Partition (int [] arr,int low,int high) {     int pivot=arr[low ];//takes the first element of the subsequence as the pivot element while     (Low < High)     {         //from the back-to-front half of the first element while looking for the one that is less than the pivot element while         (Low < High & & Arr[high] >= pivot)         {             --high;         }         Swap this element smaller than the pivot element to the first half of         swap (Arr[low], Arr[high]);         Look for the first element that is greater than the pivot element while in the first half of the trip         (Low 

Average efficiency O (NLOGN), suitable for sorting large lists.
The total time of this algorithm depends on the location of the pivot value, and the first element as the hub may lead to the worst use case efficiency of O (n²). If the number is basically orderly, the efficiency is the worst. The intermediate value of the option as the pivot, the efficiency is O (NLOGN).
Based on the division and treatment method.



Vii. sequencing of Heaps
Maximum heap: The key for any non-endpoint is greater than or equal to its left and right child's keyword, at which point the node at the top of the heap is the largest of the entire sequence.
Thought:
(1) Make i=l, and make temp= KL;
(2) Calculating the left child j=2i+1 of I;
(3) If j<=n-1, then turn (4), otherwise turn (6);
(4) Compare KJ and kj+1, if kj+1>kj, then make j=j+1, otherwise j unchanged;
(5) Compare temp and KJ, if kj>temp, then make Ki equals kj, and make i=j,j=2i+1, and turn (3), otherwise turn (6)
(6) Make Ki equal to temp, end.

void Heapsort (Seqiast R) {///to R[1..N] for heap sorting, may wish to use r[0] to do the staging unit       int I;      Buildheap (R);//r[1-n] is built into the initial heap for    (i=n;i>1;i--)//to the current unordered area r[1..i] heap sorting, a total of n-1 trip.    {             r[0]=r[1];        R[1]=r[i];        R[I]=R[0]; Exchange             heapify (r,1,i-1) between the top of the heap and the last record in the heap;  Re-r[1..i-1] to heap, only r[1] may violate heap properties      }   

The time of the heap sequencing consists mainly of the time overhead of building the initial heap and rebuilding the heap repeatedly, both of which are implemented by invoking Heapify.

The worst time complexity for heap sorting is O (NLGN).     The average performance of heap sorting is closer to the worst performance.     Heap sorting is not appropriate for files with fewer records due to the number of comparisons required to build the initial heap. A heap sort is an in-place sort, with a secondary space of O (1), which is an unstable sort method.


The difference between a heap sort and a direct insert sort:
In order to select the smallest record of a keyword from R[1..N], a n-1 comparison must be made, and then the smallest record of the keyword is selected in R[2..N], and n-2 is required. In fact, there are a number of comparisons that are likely to have been made in the previous n-1 comparison, but because the previous n-2 did not retain these comparisons, the comparison was performed repeatedly when the latter was sorted.
Heap sorting saves some of the comparison results by using a tree structure, which reduces the number of comparisons.


Eight, topological sort
Example: The sequence of students ' elective course scheduling
Topological ordering: The process of arranging the vertices of a forward graph into a linear sequence in accordance with their precedence relationship.
Method:
Select a vertex without a precursor in the graph and output
Delete the vertex and all arcs that end with it
Repeat these two steps until all vertices are output (topology sequencing succeeds), or when no precursor vertices are present in the diagram (with loops in the diagram).

void Topologicalsort ()/* output topological sort function.     If G has no loop, then output a topological sequence of the vertex of G and return OK, otherwise return error*/{int indegree[m];     int i,k,j;     char N;     int count=0;     Stack Thestack; Findindegree (G,indegree);//For each vertex indegree[0....num] initstack (thestack);//Initialize stack for (i=0;i<g.num;i++) Co Nsole.     WriteLine ("+g.vertices[i].data+" in the "+indegree[i");     for (i=0;i<g.num;i++) {if (indegree[i]==0) Push (Thestack.vertices[i]);     } console.write ("Topological sort output order:"); while (Thestack. Peek ()!=null) {Pop (thestack.         Peek ());         J=locatevex (G,n); if (j==-2) {Console.WriteLine ("Error occurred, program ended.             ");         Exit ();         } console.write (G.vertices[j].data);         count++;             for (P=G.VERTICES[J].FIRSTARC;P!=NULL;P=P.NEXTARC) {K=p.adjvex; if (! (         --INDEGREE[K])) Push (G.vertices[k]); }} if (Count<g.num) Cosole.writeline ("The graph has loops, there is an error and cannot be sorted.     "); Else        Console.WriteLine ("Sort succeeded.  "); }

The time complexity of the algorithm O (n+e).



Nine, tournament ranking
The algorithm idea for tournament sequencing is similar to sporting events.
First, the n data element 22 group, respectively, by the keyword comparison, to get N/2 comparison of the winner (the key word), as the first step to compare the results of the preservation,
Then the n/2 of the data elements 22 groups, respectively, by the keyword comparison, ..., and so on, until the selection of a keyword the smallest data element.

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define SIZE 100000     #define MAX 1000000 struct Node {long num;//keyword char str[10]; int lastwin;//last wins opponent Int killer;//defeated opponent Long times;//tournament number}data[size]; Long comparenum=0; Long exchangenum=0;     Long read (char name[])//Read the data in the file A.txt and store it in the array data[]; the last number of data returned {FILE *FP;     Long I=1;     Fp=fopen (name, "RW");     FSCANF (FP, "%d%s", &data[i].num,data[i].str);         while (!feof (FP)) {i++;      FSCANF (FP, "%d%s", &data[i].num,data[i].str); } return (I-1);     } long create (long num)//Create winner Tree, return the Champion (minimum) in array data[] subscript {int i,j1,j2,max,time=1;     Long min;//records the subscript for the current championship for (I=1;pow (2,i-1) <num;i++);         Max=pow (2,i-1);//Find leaf node number for (i=1;i<=max;i++)//Initialize leaf node {data[i].killer=0;         data[i].lastwin=0;         data[i].times=0;     if (i>num) Data[i].num=max;  } for (i=1;i<=max;i+=2)//First round match   {++comparenum;             if (data[i].num <= data[i+1].num) {data[i].lastwin = i+1;             Data[i+1].killer=i;             ++data[i].times;             ++data[i+1].times;         Min=i;             } else {data[i+1].lastwin=i;             data[i].killer=i+1;             ++data[i].times;             ++data[i+1].times;         min=i+1; }} j1=j2=0;//records the subscript while (Time <= (max)/log (2)) of consecutive two non-retired players//knockout {for (i=1;i<=max;i++ {if (data[i].times==time && data[i].killer==0)//Find a player {j2=i;//                 By default it is the later if (j1==0) in the two player//if the first position is empty, then the player who comes first comes to the j1=j2;                     else//Otherwise just come to the contestant is later, then the contestants have already arrived at the beginning of the game {++comparenum;                if (data[j1].num <= data[j2].num)//first-come player wins {Data[j1].lastwin = j2;//last win is J2          Data[j2].killer=j1;//j2 is to be J1 eliminated ++data[j1].times;                     ++data[j2].times;//two players and 1 min=j1;//minimum J1 j1=j2=0;//will j1,j2 0                         } else//similarly {data[j2].lastwin=j1;                         Data[j1].killer=j2;                         ++data[j1].times;                              ++data[j2].times;                         Min=j2;                     j1=j2=0; }}}} time++;//number of rounds plus 1} return min;//returns the champion's subscript} void Tournamentsort (lon     G num)//tournament Sort {long tag=create (num);//Returns the minimum number of subscript FILE *FP1; Fp1=fopen ("Sort.txt", "w+");//Create and open a file for write sort.txt while (data[tag].num! = MAX)//When the minimum value is not infinity {printf ("%d%s\n" , data[tag].num,data[tag].str);//Output Data fprintf (FP1, "%d%s\n", data[tag].num,data[tag].str);//Write Data DATA[TAG].N Um=max;Replace the current championship with Infinity Tag=create (num);//Returns the next champion's Subscript}} int main () {int num;     Char name[10];     printf ("Input Name of the file:");     Gets (name); Num=read (name);//Read file Tournamentsort (num);//Tournament sort printf ("comparenum=%d\nexchangenum=%d\n", Comparenum,exchangenum     ); return 0;  }


Ten, the base sort
The cardinality sort is also known as bucket ordering. Compared with the previous sorting methods described earlier, the cardinality sort differs significantly from them.
The sorting method described above is based on the comparison of data element keywords, so it can be referred to as comparison-based sorting;
The cardinality sort first assigns the data elements to be sorted into different buckets, then "collects" the data elements in each bucket.
By using this method of "assigning" and "collecting" to sort multiple keywords, the cardinality sort implements the ordering of multiple keywords.
———————————————————————————————————————
Cases:
Each card has two "keywords": Suit and face value. The order of size is:
Suit: §<¨<©<ª
Face value: 2<3< ... <k<a
The size of playing cards is based on the color comparison, the color of the card is smaller than the size of the card, the color of the same card based on the face value comparison. So, the cards are arranged in order from small to large, and the following sequences can be obtained:
§2,...,§a,¨2,...,¨a,©2,...,©a,ª2,...,ªa
This sort is equivalent to a two keyword sort, which is generally implemented in two ways.
One: can be divided into four stacks according to the suit (each pile of cards with the same suit), and then in each pile of cards and then the face value from small to large order, and finally put the order of four stacks of cards from small to large order stacked together to get the results sorted.
Second: You can sort by the face value of 13 piles (each card has the same face value), and then the 13 cards in the face value from small to large stacking together, and then the whole deck according to the order of the suit and then divided into four piles (each pile of cards have been in the order of the face value from small to large), Finally, the four stacks of cards are sorted by the suit from small to very combined.
———————————————————————————————————————
Implementation method:
Highest priority (most significant Digit first) method, referred to as MSD method: K1 Sorting group, the same group of records, the key code k1 equal, and then the group by the K2 sort into subgroups, after the key code to continue such a sorting group, Until the sub-groups are sorted by the most-important KD. By connecting the groups together, an ordered sequence is obtained.
The lowest bit first (Least significant Digit first) method, or LSD method, starts with the KD sequence, then sorts the kd-1, repeats it until the K1 is sorted, and then gets an ordered series.

Using System; Using System.Collections.Generic; Using System.Linq; Using System.Text; Namespace Learnsort {class Program {static void Main (string[] args) {int[] arr = Cr Eaterandomarray (10);//Generate random array print (arr);//output array radixsort (ref arr);//Sort print (arr);//Output         Sorted results Console.readkey ();             } public static void Radixsort (ref int[] arr) {int imaxlength = getmaxlength (arr);         Radixsort (ref arr, imaxlength); } private static void Radixsort (ref int[] arr, int imaxlength) {list<int> List = new Li St<int> ()///Store the element after each order list<int>[] Listarr = new list<int>[10];//10 barrels char Currne tchar;//holds the current character, for example, an element 123 of 2 string currentitem;//holds the current element such as an element 123 for (int i = 0; i < Listar R.length;                 i++)//Allocate memory initialization to 10 buckets.             Listarr[i] = new list<int> (); FThe OR (int i = 0; i < imaxlength; i++)//Executes imaxlength times, imaxlength is the maximum number of digits of the element. {foreach (int number in arr)//bucket {CurrentItem = number. ToString ();//convert current element to string try {Currnetchar = currentitem[currentitem.length-i-1];} Start the bucket catch {listarr[0] from the single digit to the high. ADD (number); Continue }//If an exception occurs, press the number into listarr[0].                     For example, 5 is not a 10-digit number, the execution of the above operation will definitely have an out-of-bounds exception, this is the expected behavior, we think 5 of 10 digits is 0, so it is pressed into the bucket of listarr[0].                     Switch (CURRNETCHAR)//through the value of Currnetchar, determine which bucket it presses. {case ' 0 ': listarr[0]. ADD (number);                     Break Case ' 1 ': listarr[1]. ADD (number);                     Break Case ' 2 ': listarr[2]. ADD (number);                     Break Case ' 3 ': listarr[3]. ADD (number);                     Break Case ' 4 ': listarr[4]. ADD (number);                     Break Case ' 5 ': listarr[5]. ADD (number);                     Break Case ' 6 ': listarr[6]. ADD (number);        Break             Case ' 7 ': listarr[7]. ADD (number);                     Break Case ' 8 ': listarr[8]. ADD (number);                     Break Case ' 9 ': listarr[9]. ADD (number);                     Break                     Default:throw new Exception ("Unknow error"); }} for (int j = 0; J < Listarr.length; J + +)//To rearrange data in 10 buckets and press into List F Oreach (int number in listarr[j]. Toarray<int> ()) {list.                     ADD (number); LISTARR[J]. Clear ();//Empty each bucket} arr = list.                 Toarray<int> ();//arr points to the rearranged element//console.write ("{0} times:", I); Print (arr);//output A list of the results of a single arrangement.             Clear ();//Clear List}}//Get the maximum number of bits of the element private static int getmaxlength (int[] arr) {             int imaxnumber = Int32.minvalue;     foreach (int i in arr)//traverse to get maximum value {if (i > Imaxnumber)                Imaxnumber = i; } return Imaxnumber.tostring ().         length;//This is a bit of an opportunistic way to get the maximum number of elements ...} Output array element public static void Print (int[] arr) {foreach (int. i in arr) system.c Onsole.             Write (i.tostring () + ' \ t ');         System.Console.WriteLine (); }//produces a random array. The range of random numbers is 0 to 1000. Parameter ilength refers to how many random numbers are generated public static int[] Createrandomarray (int ilength) {int[] arr = new Int[il             Ength];             Random random = new random (); for (int i = 0; i < ilength; i++) arr[i] = random.             Next (0,1001);         return arr; }     } }

The Cardinal sort method is a sort of stability, its time complexity is O (Nlog (r) m), where R is the base to take, and M is the number of heaps, at some point, the cardinality ranking method is more efficient than other comparative sorting methods.

Summary of 10 sorting algorithms

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.