Summary of data structure (ix) sorting algorithm hodgepodge

Source: Internet
Author: User
Tags comparison sorts
Bubble Sort

Bubble sort (Bubble sort) is a simpler sort algorithm in the field of computer science. It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted. The name of the algorithm is because the larger the element will slowly "float" to the top of the sequence, hence the name. Bubble Sort Operation

The bubbling Sort algorithm works as follows: (from back to front) 1. Compare adjacent elements. If the first one is bigger than the second one, swap them both. 2. Do the same work for each pair of adjacent elements, starting from the first pair to the end of the last pair. At this point, the last element should be the maximum number. 3. Repeat the above steps for all elements except the last one. 4. Repeat the above steps each time for fewer elements until there are no pairs of numbers to compare. Sort Code

void Bubblesort (Recordlist L) {

    int i,j,k;
    int t;
    for (i = 1;i <= l.length-1;j++) {for
        (j = 1;j <= l.length-i; j + +) {
            if (L.r[j] > L.r[j+1]) {
                T = l.r[j];< C6/>L.R[J] = l.r[j+1];
                L.r[j+1] = t;

}}} A recursive implementation

of void sort (int *add,int len)
{
    int fact = 0, isorderd = 0;
    if (len <= 1 | |!add) {
        return;
    }

    while (Fact < len-1) {
        if (Add[fact] > Add[fact+1]) {
            add[fact]   ^= add[fact+1];
            ADD[FACT+1] ^= add[fact];
            Add[fact]   ^= add[fact+1];
            Isorderd    = 1;
        }
        fact++;
    }
    if (!isorderd) {
        return;
    }
    Sort (add,len-1);
}

Insert Sort

  Time complexity: The worst case is O (n^2).

  Scenario: For small-scale input, the insertion sort method is a fast sorting algorithm, so it
  is advantageous to use this algorithm in small scale.

  space complexity: it requires only one element of the auxiliary space, that is, the monitoring whistle for the element exchange, so the spatial complexity of O (1).

  Stability:  The insertion sort is stable.

  Applicability:  can be used in the array and the list of two storage methods
Illustrations

Simple Implementation

#define MAXSIZE-

typedef struct list{

    int r[maxsize+1];
    int length;

} List_array;


void Insertsort (List_array L) {
    int i,j;
    for (i = 2;i <= l.length;i++) {
        if (l.r[i]< l.r[i-1]) {
            l.r[0] = l.r[i];
            for (j = i-1; l.r[0]<l.r[j];j--)
                l.r[j+1] = l.r[j];
            L.R[J+1] = l.r[0];


}} A recursive implementation of
void sort (int *add,int len)
{
    int fact  = 0;
    int index = 0;
    int obj   = add[len-1];

    if (len <= 1 | |!add | | len > Lstlen) {
        return;
    }

    index = len-1;
    while (Fact < len-1) {
        if (Add[fact] > Add[index]) {break
            ;
        }
        fact++;
    }
    while (Index > fact) {
        Add[index] = add[index-1];
        index--;
    }
    Add[fact] = obj;
    Sort (add,len+1);
}

Select Sort

Select sort (Selection sort) is a simple and intuitive sorting algorithm. It works by selecting the smallest (or largest) element of the data element to be sorted each time, storing it at the beginning of the sequence until all the data elements to be sorted are exhausted. time complexity, and stability analysis

Select the sort interchange operation between 0 and (n-1) times. The comparison operation for the selection sort is between n (n-1)/2 times. The assignment of the select sort is between 0 and 3 (n-1) times.

Select Sort is an unstable sorting algorithm.

void Selectsort (Recordlist L) {

    int i,j,k;
    for (i = 1;i <= l.length-1;i++) {
        k = i;
        for (j = i+1;j <= l.lenghth-1;j++) {
            if (L.r[i] < l.r[k])
                k = j;
            if (k! = i) {
                t = l.r[i];
                L.r[i] = l.r[k];
                L.r[k] = t;

}}} Above is a code in the book.
this is a recursive
void sort (int *add,int len)
{
    int fact  = 1;
    int index = 0;
    if (len <= 1 | |!add) {
        return;
    }

    index = 0;
    while (Fact < Len) {
        if (Add[fact] < Add[index]) {
            index = fact;
        }
        fact++;
    }
    if (index = = 0) {
        goto _digui;
    }
    Add[0]     ^= Add[index];
    Add[index] ^= add[0]    ;
    Add[0]     ^= Add[index];
_digui:
    sort (add+1,len-1);
}


binary Insert Sort
The binary insertion sort (binary insertion sort) is an improvement to the insertion sorting algorithm, which
, because of the sequencing algorithm, inserts the elements sequentially into the sequence that is already sorted. Since the first half of the sequence is already ordered
, we do not need to find the insertion point sequentially, and we can use the binary lookup method to speed up the search for the insertion point.
Specific Operation

In the process of inserting a new element into an ordered array, when looking for the insertion point, set the first element of the insertion area to A[low] and the end element to A[high], then the wheel will be inserted into the element with A[m], where the m= (Low+high)/2 comparison, if smaller than the reference element, Select A[low] to a[m-1] for the new insert area (i.e. high=m-1), otherwise select a[m+1] to A[high] for the new insert area (i.e. low=m+1), so that until the Low<=high is not established, all elements after this position will be moved back one bit, and insert the new element into a[high+1]. Stability and complexity

The binary insertion sorting algorithm is a stable sorting algorithm, which significantly reduces the number of comparisons between keywords compared to the direct insertion algorithm, so the speed is faster than the direct insert sorting algorithm, but the number of records moved does not change, so the time complexity of the binary insertion sorting algorithm is still O (n^2), and the same as the direct insertion sorting algorithm. Additional space O (1).

Binary lookup only reduces the number of comparisons, but the number of elements moved is constant, so the time complexity is O (n^2) is correct.

void Biinsertsort (Recordlist L) {
    int i,j,k;
    int Low,high;

    for (i = 2;i <= l.lenghth;i++) {
        if (L.r[i] < l.r[i-1]) {
            l.r[0] = l.r[i];
            low = 1;
            High = i-1;
            while (low <= high) {
                mid = (low + high)/2;
                if (L.r[0] < L.r[mid]) {High
                    = mid-1;
                } else{Low
                    = mid + 1;
                }

            }

            for (j = i-1;j >= low;j--) {
                l.r[j+1] = l.r[j];
                L.r[low] = l.r[0];}}}




Merge Sort

Complexity of Time: O (nlog2n)

Space complexity: Only one space is required O (N)

Stability: Stable sequencing

void merge (int *add,int len)
{
    int LenA  = 0   , LenB = 0,lenc = 0,lentmp = 0;
    int *ARRC = NULL;

    if (len <= 1) {
        return;
    }
    ArrC = (int *) malloc (len*sizeof (int));
    lentmp = LEN/2;

    Merge (add,lentmp);
    Merge (&add[lentmp],len-lentmp);

    LenA   = 0, LenB = lentmp;
    Lenc   = 0;

    while (LenA! = lentmp) && (LenB! = len)) {
         if (Add[lena] < Add[lenb]) {
              Arrc[lenc] = Add[lena];
              lena++;
         } else{
              Arrc[lenc] = Add[lenb];
              lenb++;
         }
         lenc++;
    }

    if (LenA = = lentmp) {
         while (LenB < len) {
             arrc[lenc++] = add[lenb++];}
    } else if (LenB = = len) {
         while (LenA < lentmp) {
             arrc[lenc++] = add[lena++];}
    } else{
         //printf ("All ok!\n");
    }

    memcpy (add,arrc,len*sizeof (int));

    Free (ArrC);
}


Quick Sort

Quick Sort (Quicksort) is an improvement to the bubbling sort. Quick Sort by C. A. R. Hoare was introduced in 1962. Its basic idea is: by a trip to sort the data to be sorted into two separate parts, one part of all the data is smaller than the other part of all the data, and then the two parts of the data are quickly sorted by this method, the entire sorting process can be recursive, so as to achieve the entire data into an ordered sequence.

Set to sort the array is a[0] ... A[n-1], the first arbitrary selection of data (usually the first number of the array) as the key data, and then all the smaller than the number of it in front of it, all the larger than its number is placed behind it, this process is called a fast sort of a trip. It is important to note that fast sorting is not a stable sorting algorithm, that is, the relative position of multiple identical values may change at the end of the algorithm.

A quick sort of algorithm is:

(1) Set two variables I, J, when the Order begins: i=0,j=n-1;

(2) The first array element as the key data, assigned to the key, that is, key=a[0];

(3) Starting from J forward search, that is, from the beginning to search forward (j--), find the first value less than key A[j], will a[j] and A[i] interchange;

(4) From I start backward search, that is, to start backward search (i++), find the first greater than key A[i], will a[i] and A[j] interchange;

(5) Repeat 3rd, 4, until i=j, (3,4 step, did not find the value of the match, that is, 3 a[j] is not less than the key,4 A[i] is not larger than the time to change the value of J, I, so j=j-1,i=i+1 until found. Locate the value that matches the condition, and the J pointer position does not change when I exchange it. In addition, I==J this process must be exactly when the i+ or J completes, at which time the loop ends).

Code Implementation

int __quicksort (recordlist l,int low,int high) {

    l.r[0] = L.r[low];
    while (Low < high) {when

        (Low < high && L.r[high] >= l.r[0])
            --high;
        L.r[low] = L.r[high];
        while (Low < high && L.r[low] < l.r[0])
            ++low;
        L.r[high] = L.r[low];

    }
    L.r[low] = l.r[0];

    return low;

}


void Quicksort (Recordlist l,int low,int high) {

    if (Low < high) {
        pos = quicksort (L,low,high);
        __quicksort (l,low,pos-1);
        __quicksort (L,pos+1,high);

    }

}
Hill Sort

The Hill sort (Shell sort) is a sort of insertion. Also known as narrowing incremental sorting, is a more efficient and improved version of the direct insertion sorting algorithm. Hill Sort is a non-stable sorting algorithm. The method is due to DL. The shell was named after it was introduced in 1959. Hill sort is to group records by a certain increment of the subscript, sorting each group using the direct insertion sorting algorithm; As the increments gradually decrease, each group contains more and more keywords, when the increment is reduced to 1 o'clock, the entire file is divided into a group, the algorithm terminates

First, take an integer less than n D1 as the first increment, grouping all the records in the file. All records with a multiple of D1 are placed in the same group. First, the direct insertion sort is performed within each group, and then the second increment d2<d1 repeats the above groupings and sorts until the increment =1 (< ... <d2<d1) is taken, that is, all records are placed in the same group for direct insert sorting.

Comparing the number of distant distances (called increments) so that the number moves across multiple elements, a comparison can eliminate multiple element exchanges. D.l.shell realized this idea in 1959 in a sort algorithm named after him. The algorithm first sorts the group of numbers by an increment d into groups, each group of records of the subscript difference D. Sort all the elements in each group, then use a smaller increment to do it, and then sort them in each group. When the increment is reduced to 1 o'clock, the entire number to be sorted is divided into a group, and the sort is completed.

The average initial fetch sequence is half-increment, and then halved each time until the increment is 1.

Here's the previous figure

Complexity of Time:

O (n^ (3/2)) ~ O (n^2)

Spatial complexity is still the same as direct insertion, requiring only one secondary space.

Stability: An unstable sorting algorithm

void Shellsort (recordlist l,int dk) {int i,j;
            for (i = dk=1;i <= l.length;i++) {if (L.r[i] < L.R[I-DK]) {l.r[0] = L.r[i];
            for (j = i-dk;j >0 && (l.r[0] < l.r[j]); J-= DK) {L.R[R+DK] = l.r[0];
    }}}} void shellsort_s (Recordlist l,int dlta[]) {int k;
for (k = 0;k <l.length;k++) shellsort (L,dlta[k]);
    A recursive implementation of void sort (int *add,int len,int gap) {int FST = 0, sec = 0;

    int index = 0/*, gap = len/2*/;
    if (len <= 1 | |!add) {return;
    } if (0 = = gap) {return;
            }//while (Gap! = 0) {for (fst=gap;fst<len;fst++) {index = add[fst];  for (SEC=FST;SEC&GT;=GAP;SEC-=GAP) {if (Index < ADD[SEC-GAP]) {add[sec] = add[sec-
                GAP];
                }else{break;
        }}//end for[sec] add[sec] = index; }//enD FOR[FST]//gap/= 2;
    Display (Add,len);
}//end While[gap] Sort (ADD,LEN,GAP/2);
 If you remove the comment, it is non-recursive.

View Original: http://zmrlinux.com/2015/12/20/%e6%95%b0%e6%8d%ae%e7%bb%93%e6%9e%84%e5%b0%8f%e7%bb%93%ef%bc%88%e4%b9%9d% ef%bc%89%e6%8e%92%e5%ba%8f%e7%ae%97%e6%b3%95%e5%a4%a7%e6%9d%82%e7%83%a9/

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.