Full Solution sorting algorithm

Source: Internet
Author: User

Full Solution sorting algorithm

Sort: The element in the table is rearranged, and the element in the table satisfies the process of incrementing or decreasing by keyword. For convenience, it is common to require that the tables in your computer be ordered by the keyword. The exact definition of the sort is as follows:

input:n Records r1,r2, ..., rn the corresponding keyword is k1,k2,...,kn.

output: a rearrangement of the input sequence R1 ', R2 ', ..., Rn ', which makes it possible to have K1 ' <=k2 ' <=...<=kn ' (where "<=" is done to replace other compared-size symbols).

The stability of the algorithm: if the table to be sorted with two elements ri, Rj, its corresponding keyword Keyi=keyj, and before the pre-order RI in RJ before, if the use of a sort algorithm, RI is still in front of RJ, it is called this, otherwise called sorting algorithm is stable, otherwise called sorting algorithm is not stable. It should be noted that the stability of the algorithm does not measure the merits and demerits of an algorithm, it mainly describes the nature of the algorithm.

Note: For an unstable sorting algorithm, simply cite an example of a set of keywords to illustrate its instability.

In the process of sorting, according to whether the data element is completely in memory, the sorting algorithm can be divided into two categories: internal sorting refers to the ordering of elements in memory during the sorting; external sorting means that elements cannot be stored in memory all at the same time during sorting, and must be kept in the process of sorting as required. The sort of movement between external memory.

-In general, the internal sorting algorithm performs two operations during execution: compare and move. By comparing two keywords, determine the relationship of the corresponding elements, and then move the elements to achieve order. Of course, not all internal sorting algorithms are based on comparison operations, in fact, cardinality sorting is not based on comparisons.

The performance of the internal sorting algorithm depends on the time complexity and space complexity of the algorithm, and the time complexity is usually determined by the number of comparisons and moves.

Without special instructions, this article defaults to ascending sort. I. Insert Sort

Insertion sorting is a simple and intuitive sorting method, the basic idea is that each time a record to be sorted, by its keyword is inserted into the previous sequence of the subsequence, until all the records are inserted.

The idea of inserting sort leads to three important sorting algorithms: Direct insert Sort, binary insert sort, hill sort.

1. Direct Insert Sort

Thought:

The basic operation for inserting a sort is to find and insert in an ordered table. The 1th record of the sequence is first considered an ordered subsequence, and then inserted from the 2nd record one after the other until the entire sequence is ordered. The entire sorting process is n-1.

Algorithm Description:

1) Find the insertion position of L (i) in l[1...i-1] K.
2) all elements in l[k...i-1] are moved back one position.
3) Copy L (i) to L (k).

For example, the initial arrangement of a set of records that are known to be sorted is as follows:

(1-1)

Assuming that the first 4 records have been rearranged in the order of key-to-increment in the sort process, forming an ordered sequence with 4 records

                                                        (1-2)

The 5th (i.e., 76) record of the formula (1-1) is inserted into the above sequence to obtain a new ordered sequence with 5 records.
The first thing to do is to look in the sequence of the formula (1-2) to determine where R (76) should be inserted, and then insert it.
Assuming that from R (97) to the left of the sequential search, because of 65<76<97, then R (76) should be inserted between R (65) and R (97), resulting in the following new ordered sequence
{R (g), R (+), R (6th, R (), R (97)} (1-3)
The process of calling the slave (1-2) to the formula (1-3) is a direct insert sort.
In general, the operation of the first direct insert sort is: After inserting a record r[i] in an ordered subsequence containing I-1 Records r[1..i-1], it becomes an ordered subsequence containing 4 records R[1..I]; and, like the sequential lookup, In order to avoid the array subscript out of bounds during the search for the insertion position, set the lookout at R[0]. In the process of searching forward from I-1, the record can be moved back at the same time. The entire sorting process is n-1, that is, the 1th record of the sequence is considered an ordered sub-sequence, and then inserted from the 2nd record one after the other until the entire sequence is ordered.

Note:

The r[0] is set up to be used as a temporary storage and to determine the array boundaries (avoid array subscript out of bounds). The algorithm is written in r[0] as the Sentinel (r[0) does not save data, the actual application of the available variables in lieu of temporary storage, but avoid array subscript out of bounds).

Example:

Algorithm:

voidInsertsort (Elemtype a[],intN) {  inti,j;  for(i=2; i<=n;i++) {//Insert A[2]-a[n] into the previously sorted sequence      if(a[i].key<a[i-1].key) {//if the key code of A[i] is less than its predecessor, it is necessary to insert a[i] into the ordered tablea[0]=a[i];//Copy as Sentinel           for(j=i-1; a[0].KEY&LT;A[J].KEY;--J) {//find the insertion position from behinda[j+1]=A[J];//move back .} a[j+1]=a[0];//Copy to insertion location      }  }}

Performance Analysis:

space Efficiency : Only a constant number of auxiliary units are used, thus the space complexity is O (1).

time Efficiency : During the sorting process, the operation of inserting elements one by one into an ordered sub-table is n-l, each operation is divided into comparison keywords and moving elements, and the number of comparisons and moves depends on the initial state to be sorted. In the best case, the elements in the table are ordered, at which point each element is inserted, and the time complexity is 0 (n), which is only compared once without moving the element.
In the worst case, the order of the elements in the table is exactly the same as the order of the elements in the ordering result (reverse), the total number of comparisons reached the maximum, the total number of moves also reached the maximum, for.
On average, consider that the elements in the table to be sorted are random, at which point the best and worst-case averages can be taken as the average time complexity, with the total number of comparisons and the total number of moves.
Thus, the time complexity of inserting the sorting algorithm directly is the time complexity of the binary insertion sorting algorithm, but for the sort table with the smaller data volume, the binary insertion sort tends to show good performance.

Stability: Every time you insert an element, you always compare and then move from back to front, so there is no case where the same element changes relative to position, that is, the direct insert sort is a stable sorting method.
Applicability: the direct insertion sorting algorithm is suitable for linear tables of sequential and chained storage. When chained, you can find the location of the specified element from the go-back. Note: Most sorting algorithms apply only to linear tables that are stored sequentially.

2. Binary Insert Sort

Thought:

The basic operation of inserting a sort is to find and insert in an ordered table, noting that the algorithm always moves the elements in the edge comparison, and the following separates the comparison from the move operation, finds the position where the element is to be inserted, and then moves all the elements after the insertion position uniformly. Binary insert sorting is optimized for find, primarily reducing the number of comparisons between keywords.

Take the intermediate node of the ordered table, compare with r[0], find the left Antimeron table, less than r[0] find the right Antimeron table, and loop until the low is high.

Algorithm:

voidInsertsort (Elemtype a[],intN) {  intI,j,low,high,mid;  for(i=2; i<=n;i++) {//Insert A[2]-a[n] into the previously sorted sequence      if(a[i].key<a[i-1].key) {//if the key code of A[i] is less than its predecessor, it is necessary to insert a[i] into the ordered tablea[0]=a[i];//Copy as Sentinellow=1; high=i-1;  while(low<High ) {Mid= (Low+high)/2;//take the middle point                if(a[mid].key>a[0].key) high=mid-1;//Find left Antimeron table                ElseLow=mid+1;//Find right Antimeron table           }                   for(j=i-1; a[0].KEY&LT;A[J].KEY;--J) {//find the insertion position from behinda[j+1]=A[J];//move back .} a[j+1]=a[0];//Copy to insertion location      }  }}

From the above algorithm, it is not difficult to see that the binary insertion sort is only to reduce the number of comparison elements, approximately, the comparison is independent of the initial state of the table to be sorted, only depends on the number of elements in the table n, and the number of moves of the element has not changed, it depends on the initial state of the table to sort. Therefore, the time complexity of the binary insertion sort is still. Binary insert sort is a stable sorting method.

Note: For loop

For loop form: for (expression 1; expression 2; expression 3), Flowchart:

3. Hill sort

From the previous explanation, it is not difficult to see that the direct insertion sorting algorithm is suitable for the basic ordered sort table and the data volume of the sort table. Based on these two points, 1959 D.l.shell proposed a hill sort, also known as narrowing the incremental sort.

Thought:

First, the table to be sorted into a number of shapes such as L[i, I+d, i+2d,... I+KD] "special" sub-table, respectively, the direct insertion of the order, when the entire TABLE element has been "basic order", then the whole record-the direct insertion of the order.

Algorithm Description:

First take a step D1 less than N, all the records in the table are divided into D1 groups, all the records with multiples of D1 are placed in the same group, the direct insertion sort is done in each group, and then the second step d2<d1, repeating the process until the dt=1 is taken, that is, all records are placed in the same-group, Then the direct insertion of the sort, because at this time has a good locality, it can quickly get the final result.

Settings for an incremental sequence:

So far, one of the best incremental sequences has not been obtained, and the approach proposed by Hill is that.

Example:

Algorithm:

voidShellsort (Elemtype a[],intN) {//The following modifications are made to the sequential table as a hill insert sort, compared to the direct insert sort://1. The increment of the recording position is DK, not 1//2.r[0] is just a staging unit, not a sentry, when j<0, the insertion position is        for(dk=len/2; dk>=l; dk=dk/2)//Step Change           for(i=dk+l;i<=n;++i)if(A[i].key<a[i-dk].key) {//need to insert a[i] into an ordered Delta sub-tablea[0]=a[i];//temporary presence A[0]                    for(j=i-dk;j>0&&a[0].key<a[j].key;j-=DK) A[j+DK]=A[J];//record and move back to find the inserted locationa[j+dk]=a[0];//Insert              }//if}

Performance Analysis:

space Efficiency : Only a constant number of auxiliary units are used, with a spatial complexity of 0 (1).

time Efficiency : Because the time complexity of the hill sort depends on the function of the increment sequence, which involves the unsolved problems in mathematics, the time complexity analysis is more difficult. When n is in a certain range, the time complexity of hill sorting is about 0 (n13). In the worst case, the time complexity of hill sorting is 0 (n2).

stability : When records of the same keyword are divided into different sub-tables, the relative order between them may change, so the hill sort is an unstable sort method. For example, table l={3, 2 ', 2}, after a trip to sort, l={2, 2 ', 3}, the final sort sequence is also l={2, 2 ', 3}, obviously, the relative order of 2 and 2 ' has changed.

Applicability : The hill sorting algorithm applies only when the linear table is in the case of a sequential table.

--------------------------------------------------------------------------------------------------------------- ----------------------

Not to be continued

Reproduced must be reproduced in the words, the original author and the original post address.

Full Solution sorting algorithm

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.