In this impetuous society, many people just paste an algorithm, run one side, even if understand, we should sink the heart to

Source: Internet
Author: User
Tags stdin

1. overview

Sorting is an important operation in computer programming, and its function is to rearrange an arbitrary sequence of data records (or Records) into a sequence ordered by the Keyword.

For the sake of description, we define the sort First:

Assuming that the sequence of N Records is {r1,r2,r3,..., Rn}, its corresponding keyword sequence is {k1,k2,k3,..., Kn}, to determine a sequence whose keywords satisfy a non-descending (or Non-incrementing) relationship, which is called Ordering.

This sort is stable if any of the two records in the sequence of N records are in the same order before and after Sorting.

For example: in the original sequence of RI in RJ before, 1<=i<=n,1<=j<=n,i!=j, after the order is still RI ranked before rj, this is the stable sort, conversely, unstable sort.

If the sort is only done in ram, it is called an internal sort, and if it involves external memory (such as disks, ssds, floppy disks, Flash memory, etc.) It is called an external sort.

Why there are two ways, it is very simple, if the processing of data is very large, can not be fully read into memory at a time, you need to use external memory to Sort.

2. Insert Sort

  2.1 Direct Insert Sort

    The simplest sort, the basic operation is to insert a record into the ordered table in order to get a new, record length plus 1 of the ordered Table.

Simple Proof:

Assuming that the sequence of N Records is {r1,r2,r3,..., Rn}, its corresponding keyword sequence is {k1,k2,k3,..., Kn}, and the first record of the sequence is an ordered SEQUENCE.

The first step takes the second record of the sequence, inserts the proper position of the ordered sequence, and makes it orderly;

Assuming the order of the original ordered sequence after the first n-2 step;

At step n-1, when the sequence of N Records is selected as the nth record of {r1,r2,r3,..., Rn}, and the order is inserted into an orderly sequence, the ordered sequence after step n-1 is still orderly.

The certificate is Completed.

So how do you insert the proper position of an ordered sequence?

When a sequence of n Records is selected for the first record in {r1,r2,r3,..., Rn}, the previous i-1 records are in order, the first record is compared to the size of the i-1 record, and if the first record is less than the I-1 record, then the interchange is then searched forward from the i-2 Record. During the search process, whenever a record larger than the I record is encountered, the current record is moved back one position until a record is less than or equal to the I record or the No. 0 position is searched Forward.

The algorithm is as Follows:

         

Insertsort

Time complexity of the algorithm:

The basic operation for sorting is to compare the keyword size and move the record, when the sorting sequence is reversed and the keyword is not repeated with the most time Complexity. Simply prove it:

The first record of the election, in order to operate, the longest but the search to the No. 0 position, that is, the comparison i, moving i+1 times;

If there are N records to be n-1 the selection of records, if each search to the No. 0 position, that is, each time the most frequent, moving the most times, then always add up is the total comparison of the most times, the total movement of the most Times. A preceding sentence embodies an algorithm strategy, greedy algorithm. This algorithm is not necessarily correct, we use contradiction to prove correctness here.

It is assumed that the total number of moves in this construction process, the total number of comparisons is not the most, that is, there is a larger value,

We always choose the most, if there is a larger value, it means that the selection is not the most, which is contradictory to our construction process, so the assumption is not tenable.

So how do you determine that the sequence that moves most times is the reverse sequence when you compare the most times?

Very simple, if not every time is in reverse order, then there must be a select Not search to the No. 0 position to stop the forward search, because found a not less than (or not greater Than) the records of the first Record.

The certificate is Completed.

Maximum number of moves:

          

Maximum number of comparisons:

          

2.2 Other Insert Sort

      Binary insert sort, because the basic operation of the insertion sort is to find and insert in an ordered table, we can use binary lookup to implement the Find Operation.

The correctness of the algorithm is proved to be the same as the direct insert sort, but the process of finding is different.

      

Binsertsort

       

Time complexity of the algorithm:

Although the time complexity of the lookup process is

, when I was big enough

But the maximum number of moves is constant, so the algorithm time complexity is still

            

  2.3 Hill Sort

    first, the entire waiting sequence is divided into several sub-sequences, the insertion sort is performed separately, and the whole sequence is basically ordered, and then a direct insertion is ordered for All.

Its proof involves some unsolved problems in mathematics, and is interested to see the relevant papers, generally without the Algorithm's internal ordering.

3. Exchange Sorting

 3.1 Bubble sort          

first, the 1th position of the keyword and the 2nd record of the keyword comparison, in reverse order, that is, the first position of the keyword is larger than the second position of the keyword, then the two records are exchanged, and then compare the 2nd position of the keyword and the 3rd position of the key word size, in reverse order, then Exchange records, and so On.

Simple Proof:

Assuming that the sequence of N Records is {r1,r2,r3,..., Rn}, its corresponding keyword sequence is {k1,k2,k3,..., Kn},

The 1th step starts with the 1th record, and in turn compares the key size with the record of the nearest subsequent position, if it is reversed, then the exchange, when the n-1 record and the nth record are compared with the keyword, the largest record of the keyword must be in nth position (why?). You want to, each time the key word moved backward, The comparison is of course the largest in the last side, the ordered sequence is the nth record

Assuming that step n-2 starts from the 1th record to the end of the 1th record, each record compares the keyword size to the record at the nearest subsequent position, and if it is reversed, the interchange is reversed and the record with the larger keyword is added to the ordered sequence, and the ordered sequence is 3rd to n records

Step n-1, because the unordered sequence only the first two, compared once, directly into the ordered sequence, after joining, ordered sequence is the 1th record to the nth Record.

The certificate is Completed.

      

Bubblesort

Time complexity of the algorithm:

If the sequence containing n records {r1,r2,r3,..., Rn} is in reverse order by keyword size, The total time complexity is the Highest.

, so the total time complexity is

            

3.2 Quick Sort

      By dividing the backlog of records into two separate parts, one of which is smaller than the keywords in the other, you can continue to sort the records in order to achieve the Sequence.

Here is an algorithm strategy-the division Method. A problem is divided into sub-problems, and then solve sub-problems, and finally merging is the solution of the original Problem.

Implementation: first arbitrary selection of a record, usually the first record, as pivot Pivot. Defines two pointer low and high, pointing to the starting and ending points, respectively. High starts at the point where the first keyword is smaller than the pivot, then the position of low is searched backwards, The First keyword is larger than the pivot record, and the record (low

      

QSort

Algorithm time Complexity Analysis:

From the fast sequencing process we can get the following equation:

Worst Case Scenario:

T (n) =t (n-1) +n (n>=2,n∈n+, Why is this range, equal to 1 when the direct exit, do not compare; only one record compares what)

T (1) =0,t (2) = 2;

T (n) is the workload of the total problem, and N is the amount of work that divides the Process. The time complexity analysis of the algorithm, the general concern is the execution times of the key statement, here The comparison operation is the key Statement. The description is called the key statement, the most executed statement is called the key Statement.

Why the amount of work in the division process is n, must ah, no matter how you play, each time the pivot and the pivot in the sequence of all records of the keyword comparison size, until low equals high. That is, a total of n comparisons.

The arguments in the T function represent the sequence length under the Problem.

The worst case scenario, that is, you compare all the numbers every time you bitter, but you get only one sub-sequence each time, only 1 less than the length of the Sequence.

This recursive equation is not very familiar, whether you use a recursive tree or accumulation method can easily get

              

So the worst-case time complexity is O (n2).

Best Case:

T (n) =2t (n/2) +n

Get two equal sub-sequences at a Time. Why is it? Assuming that each of the two sub-sequences after each partition is a and b,a+b represents the total workload of the two sub-sequences during the partitioning process, consider the well-known Cauchy inequality, and you know that the minimum primitive is the smallest if and only when a=b.

It is easy to get the best time complexity by the main theorem, but it is better to know the reason why, and we take the derivation process.

          

So the best time complexity is O (nlog2n)

4. Testing

  Full code

    

    

#include <stdio.h>#include <stdlib.h>#include <conio.h> #define MAXSIZE 100typedef struct_recordtype{intKey Intname;} recordtype;typedef struct_seqlist{recordtype R[maxsize + 1]; Intlength;} Seqlist;void Insertsort (seqlist *L) {for (int i = 2; i <= l->length; i++/* * Initial selection of the 1th element as an ordered sequence, the first step selects the 2nd element of the sequence */{if (l->r[i].key < l->r[i-1].key)/* First compares the size of the element I and the i-1 element, and if the element i is less than the I-1 element, the interchange */{l->r[0] = l->r[i]; l->r[i] = l->r[i-1]; Int j = 0; For (j = i-2; L->r[0].key < l->r[j].key;--J)/* then search forward from the I-2 element, and in the search process, whenever an element greater than element I is encountered, move the current element back one position until an element is less than or equal to the first element or the No. 0 position is Searched.{l->r[j + 1] = l->r[j]; } l->r[j + 1] = l->r[0]; }}}void Binsertsort (seqlist *L) {int low = 0; int high = 0; int m = 0; for (int i = 2; I <=l->length; i++/* * Initial selection of the 1th element as an ordered sequence, the first step selects the 2nd element of the sequence */{l->r[0] = l->r[i]; Low = 1; High = I-1; While (low <=high)/* binary Find */{m = (low + HIGH)/2; If (l->r[0].key < L->r[m].key) high = M-1; ElseLow = m + 1; } for (int j = i-1; J >= High + 1;--J) {l->r[j + 1] = l->r[j]; }/* locate the corresponding insertion position, and move the element corresponding to the insertion position to the i-1 position */L->r[high + 1] = l->r[0]; }}void Bubblesort (seqlist *L) {recordtype tmp; BOOL swap = False; for (int i = 0; i < l->length-1; i++)/* Total n-1 step */{swap = False; for (int j = 1; J <l->length-i; + +)j)/* each step starts from the 1th element to the end of the n-i-1 element, and each element compares the keyword size to the nearest trailing position, and is exchanged if in reverse order */{if (l->r[j].key > l->r[j + 1].key) {swap = True; TMP = l->r[j + 1]; L->r[j + 1] = l->r[j]; l->r[j] =tmp }} if (swap = = False) break; /* If there is no record movement when comparing the keyword size, the previous record has been ordered by keyword */}}int partition (seqlist *l, int low, intHigh) {l->r[0] = l->r[low]; /* in a quick sort, first select any record, usually the first record, as pivot pivot */RecordType tmp; While (low <high)/* if low==high, it means that a quick sort has searched all the records and found the proper position of the pivot so that the key of the record on the left of the pivot is less than or equal to the key of the pivot to the right is greater than or equal to the pivot */{while (low < high) && (l->r[0].key > L->r[low].key) + +Low While (low < High) && (l->r[0].key < l->r[high].key))--High If (low <High) {tmp = l->r[low]; l->r[low] = l->r[high]; l->r[high] =tmp } low = low + 1; High = High-1; } returnlow;} void QSort (seqlist *l, int low, intHigh) {/* divides a sequence recursively into multiple sub-sequences until the size of the Sub-problem does not exceed 0 */if (low <High) {int Pivotpos = partition (l, n, high);/* divides sequence l->[low...high] in Split */QSort (l, Pivotpos + 1, high);/* recursive ordering of Gaozi */QSort (l, lo, pivotPos-1);/* recursive ordering of low sub-tables */}}int sum (seqlist *l,intN) {if (n > 0) return sum (l, n-1) + l->r[n].key; else return 0;} int main (void{freopen ("in.txt", "r"), stdin); Seqlist *l = (seqlist*) malloc (sizeof(seqlist)); scanf ("%d", &l->length); for (int i = 1; i <= l->length; i++) {scanf ("%d", &l->r[i].key); } insertsort (l); printf ("straight Insertion sort:\n"); for (int i = 1; i <= l->length; i++) {printf ("%d", l->r[i].key); } printf ("\ n"); Fseek (stdin, 0, 0); scanf ("%d", &l->length); for (int i = 1; i <= l->length; i++) {scanf ("%d", &l->r[i].key); } binsertsort (l); printf ("Binary Insertion sort:\n"); for (int i = 1; i <= l->length; i++) {printf ("%d", l->r[i].key);} printf ("\ n"); fseek (stdin, 0, 0); scanf ("%d", &l->length); for (int i = 1; i <= l->length; i++
                                                                                                  
                                                                                                   r[i].key);} bubblesort (l); printf ("Bubble sort:\n"
                                                                                                   ); for (int i = 1; I <= l->le ngth; i++) {printf ("%d", l->r[i].key);} printf ("\ n"); fseek (stdin, 0, 0); scanf ("%d", &l->length); for (int i = 1; i <= l->length; i++ {scanf ("%d", &l->r[i].key),} qSort (l, 1, l->length); printf ("Quick sort:\n"); for (int i = 1; I <= l->length; i++) {printf ("%d", l->r[i].key);} printf ("\ n"); printf ("%d\n", sum (l, l->length)); getch ();}        
                                                                                                  

Test Text:

  

Test results

  

In this impetuous society, many people just paste an algorithm, run one side, even if understand, we should sink the heart to

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.