Data structure (written by Yan Weimin in C language) - internal sorting

Bubble Sort

Basic idea: If the keywords of adjacent records are reversed, they will be exchanged until there are no reversed records.

void BubbleSort(int k[], int n) {
    //Bubble sort is to bubble from bottom to top, and compare two adjacent ones
    int temp, flag;
    flag = 1;//This flag is the optimization of sorting
    for (int i = 0; i < n - 1 && flag; ++i)
        for (int j = n - 1; j > i; j--) {
            flag = 0;
            //If you don't enter the following exchange when the top two are compared, the bubbling can end early
            if (k[j - 1] > k[j]) {
                temp = k[j - 1];
                k[j - 1] = k[j];
                k[j] = temp;
                flag = 1;
            }
        }
}


selection sort

Through ni keyword comparisons, the record with the smallest keyword is selected from n-i+1 records,

And exchange with the i-th (i<=i<=n) record.

void SelectSort(int k[],int n){
    int temp, min;

    for (int i = 0; i < n; ++i) {
        min=i;//min start subscript is i
        for (int j = i+1; j < n; ++j)
            if(k[j]<k[min])
                min=j;//find the subscript of the smallest element
        //exchange
        temp=k[min];
        k [min] = k [i];
        k[i]=temp;
    }
}


direct insertion sort

The operation is to insert a record into an already sorted sorted table,

  This results in a new ordered list with records incremented by 1.

It is suitable for the basic order of the array to be sorted, and there are few records.

void InsertSort(int k[], int n) {
    int temp, j;
    for (int i = 1; i < n; i++) {
        if (k[i] < k[i - 1]) {
            temp = k[i];
            for (j = i - 1; k[j] > temp&&j>=0; --j) {
                k[j + 1] = k[j];
            }
            k[j + 1] = temp;
        }
    }
}


Hill sort

is an improvement over direct insertion sort. O(n*logn)

void ShellInsert(int k[], int n) {
    int temp, j;
    int gap=n;
    do{             
        gap=gap/3+1;
        for (int i = gap; i < n; i++) {
                temp = k[i];
                for (j = i - gap; k[j] > temp&&j>=0; j-=gap) {
                    k[j + gap] = k[j];
                }
                //The above step has been j-gap
                k[j + gap] = temp;
        }
    }while (gap>1);
}

heap sort

is an improvement over selection sort. O(n*logn)

· is a complete binary tree.

· The root node must be the largest or smallest of all nodes in the heap.

  If the numbering starts from 1, the following relationship is satisfied between the nodes:


· Sorting algorithm using heap, its basic idea is:

    - Form the sequence to be sorted into a large top heap (or small top heap)

    - At this point, the maximum value of the entire sequence is the root node at the top of the heap. remove it (that is, connect it to the end of the heap array

      Elements are exchanged, and the last element is the maximum value).

    -Then reconstitute the remaining n-1 sequences into a heap so that you get the maximum of the n elements.

    - Do this repeatedly to get an ordered sequence.

void swap(int k[], int i, int j) {
    int temp;
    temp = k[i];
    k[i] = k[j];
    k[j] = temp;
}

void HeapAdjust(int k[], int s, int n) {
    //k represents the array, s represents the parent node, n represents the number of elements
    int i, temp;
    temp = k[s];//Store the parent node that needs to be adjusted
    //i = 2*s is the left child of s
    for (i = 2 * s; i <= n; i *= 2){
        //Left child < right child, and i does not exceed n (length to be queued)
        if (k[i] < k[i + 1] && i < n)
            i++;
        //If the parent node is large, end the loop early
        if(temp>=k[i])
            break;
        //The larger of the two child nodes goes to the parent node
        k[s]=k[i];
        //The subscript of the exchanged child node is given to s
        s=i;
    }
    k[s]=temp;
}

void HeapSort(int k[], int n) {
    //In order to better reflect the concept of tree, k[0] does not participate in sorting
    int i;
    //Start from the bottom of the entire heap, build a large top heap
    for (i = n / 2; i > 0; --i)
        HeapAdjust(k, i, n);
    for (i = n; i > 1; --i) {
        swap(k, 1, i);//Swap the top element of the heap with i (the last element)
        HeapAdjust(k, 1, i - 1);
    }
}


merge sort

· Assuming that the initial sequence has n records, it can be regarded as n ordered subsequences, each subsequence has a length of 1,

  Then merge them in pairs to get [n/2] ordered subsequences of length 2 or 1; then merge them in pairs, ..., and so on.

  Until an ordered sequence of length n is reached, this sorting method is called 2-way merge sort.


#define MAXSIZE 10

// Implement the merge and put the final result in list1, which is the head pointer of the array to be sorted
void Merging(int *list1, int list1_size, int *list2, int list2_size) {
    int i, j, k, m;
    int temp[MAXSIZE];
    i = j = k = 0;
    while (i < list1_size && j < list2_size) {
        // Compare the size and put it into a temporary array
        if (list1[i] < list2[j])
            temp[k++] = list1[i++];
        else
            temp[k++] = list2[j++];
    }
    // put the rest into a temporary array
    while (i < list1_size) {
        temp[k++] = list1[i++];
    }
    while (j < list2_size) {
        temp[k++] = list2[j++];
    }
    //Temporary array overwrites list1
    for (m = 0; m < list1_size + list2_size; m++)
        list1[m] = temp[m];
}

void MergeSort(int k[], int n) {
    //recursive algorithm for merge sort
    if (n > 1) {
        int *list1 = k;//Left half head pointer
        int list1_size = n / 2;//left half size
        int *list2 = k + n / 2;//The right half of the head pointer
        int list2_size = n - list1_size;//The size of the right half
        // recursive split
        MergeSort(list1, list1_size);
        MergeSort(list2, list2_size);
        // merge one by one
        Merging(list1, list1_size, list2, list2_size);
    }
}


quicksort

· Is an improvement on bubble sort. The basic idea is to divide the records to be sorted into two independent parts through a sorting,

  The keywords of some of the records are smaller than the keywords of the other part, you can proceed to the two records respectively.

  Sort to get the entire sequence in order.

int Partition(int k[], int low, int high) {
    int point;
    //Optimization scheme, select three elements to compare the size, and put the middle one in the k[low] position
//    int m=(low+high)/2;
//    if(k[low]>k[high])
//        swap(k,low,high);
//    if(k[m]>k[high])
//        swap(k,m,high);
//    if(k[m]>k[low])
//        swap(k,m,low);
    point = k[low];
    while (low < high) {
        while (low < high && k[high] >= point) {
            // Put the ones larger than the point in the back, otherwise swap positions
            high--;
        }
        if(low==high)
            break; // end early
        swap(k, low, high);//Swap the elements
        while (low < high && k[low] <= point) {
            // Put those smaller than point in front, otherwise swap positions
            low++;
        }
        swap(k, low, high);//Swap the elements
    }//Find the position of point in the array
    return low;//When returning, low = high
}

void QSort(int k[], int low, int high) {
    int point;
    if (low < high) {
        point = Partition(k, low, high);
        // recursive call to the left part
        QSort(k, low, point - 1);
        // recursive call to the right part
        QSort(k, point + 1, high);
    }
}

void QuickSort(int k[], int n) {
    QSort(k, 0, n - 1);//Initial position, last position
}

Sort summary

How to judge whether a sorting is stable or not , for example:

Before sorting: 5, 6 (1), 1, 4, 3, 6 (2), (the first 6 is before the second 6)
After sorting: if the sorted result is 1, 2, 3, 4, 5, 6 (1), 6 (2) Then the sorting algorithm is said to be stable, that is, a stable sorting.

             If the sorted result is 1, 2, 3, 4, 5, 6 (2), 6 (1), that is, 6 (1) and 6 (2) are compared before sorting, which is an unstable sorting.





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325806962&siteId=291194637