Insertion sort of eight sorting algorithms (C language version)

Table of contents:

Eight sorting algorithms:

八大排序算法
插入排序
选择排序
交换排序
归并排序
非比较排序
直接插入排序
希尔排序
选择排序
堆排序
冒泡排序
快速排序
归并排序
计数排序

Hyperlink:
Insertion sort
Selection sort
Exchange sort
Merge sort
Non-comparison sort

1. The concept of sorting

1.1 The concept of sorting

Sorting: The so-called sorting is the operation of arranging a string of records in increasing or decreasing order according to the size of one or some keywords. Stability: Assume that there are multiple records with the same keyword in the record sequence to be sorted. If sorted, the relative order of these records remains unchanged, that is, in the original sequence, r[i]=r[j] , and r[i] is before r[j], and in the sorted sequence, r[i] is still before r[j], then this sorting algorithm is called stable; otherwise it is called unstable.
Internal sorting: sorting in which all data elements are placed in memory.
External sorting: There are too many data elements that cannot be placed in the memory at the same time. According to the requirements of the sorting process, the data cannot be moved between internal and external memory.

1.2 Application of sorting

The purpose of sorting is usually to facilitate search, or to count the most or least number of repetitions.
1. Game competition. The rules of the game are a random set of 30 pictures. The 10 people participating in the competition are required to sort the pictures from small to large within 30 seconds. The one with the least time wins.
2. Questionnaire. Randomly generate N numbers from 1 to 10000, and only keep one repeated number. Different numbers correspond to the student numbers of different students, and then sort these numbers from small to large, in order Ask your classmates to investigate.
3. Award special scholarships. There are n students in a certain university, each of whom has m courses. According to the overall performance ranking, the best k students need to be selected to award special scholarships.

2. Direct insertion sort

The basic idea of ​​direct insertion sorting:
Record the content to be sorted and compare it with the sorted sequence one by one, and insert it into the ordered sequence until the sequence to be sorted is After all the records are inserted, a new ordered sequence is obtained, which is direct insertion sort
Insert image description here
The code is as follows

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <time.h>
#include <windows.h>
#define m 1000
void IsertSort(int* arr, int n)
{
    
    
    int i;
    for (i = 1; i < n; i++)//i为待排序的第一个数下标
    {
    
    
        int end = i - 1;//end 为已排好序列的尾下标
        int tmp = arr[i];//把待排序的第一个数存起来
        //遍历已排序列,进行比较然后插入,这里我进行从小到大排序
        while (end >= 0)
        {
    
    
            if (arr[end] > tmp)//如果前面的数大,就把他往后移动一个
            {
    
    
                arr[end + 1] = arr[end];
                end--;
            }
            //否则就跳出
            else
                break;
            arr[end + 1] = tmp;
        }
    }
    //打印排序后的数据
    for (i = 0; i < n; i++)
    {
    
    
        printf("%d ", arr[i]);
    }
}
int main()
{
    
    
    int head, end,arr[m];
    //srand(初始化时间),time(直接返回时间戳)
    srand((unsigned)time(NULL));

    head = clock();
    for (int i = 0; i < m; i++)
        arr[i] = rand();//,时间不停的变化,每次产生不同的随机值
    IsertSort(arr,sizeof(arr)/sizeof(arr[0]));
    end = clock();
    //排序需要花费的时间
    printf("\n%d\n ", end - head);
    return 0;
}

Performance summary of direct insertion sort:
1. The closer the element set is to order, the higher the time efficiency of the direct insertion sort algorithm.
2. Time complexity: O(N^2)
3. Space complexity: O(1), it is a stable sorting algorithm
4. Stability: stable

3. Hill sorting

Hill sorting is also called reducing increment method.
The basic idea of ​​Hill sorting:
First select an integer, and then divide the records to be sorted into groups of this integer, and all records whose distance is this integer are grouped into the same group, and the records within each group are sorted. Pre-sort first, then insert sort.

Insert image description here
code show as below:

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <Windows.h>
#define m 10000
SheelSort(int* arr, int n)
{
    
    
  int gap = 3;
    //多趟
 for(int j=0;j<gap; j++)
     //每组进行插入排序
        for (int i =j; i < n - gap; i += gap)
        {
    
    
            //单趟
            int end = i;
            int tmp = arr[end + gap];
            while (end >= 0)
            {
    
    
                if (arr[end] < tmp)//从大到小排序
                {
    
    
                    arr[end + gap] = arr[end];
                    end -= gap;
                }
                else
                    break;   
            }
            arr[end + gap] = tmp;
        }
}
int main()
{
    
    
    int head, tail, i;
    int arr[m] = {
    
    0};
    srand((unsigned)time(NULL));
    
    for (i = 0; i < m; i++)
        arr[i] = rand()%1000;
    head = clock();
    SheelSort(arr, sizeof(arr) / sizeof(arr[0]));
    tail = clock();
    printf("%d ", tail - head);

    return 0;
}

The efficiency is as follows
Insert image description here
We can optimize it (reduce one loop, but the efficiency is still about the same, and the code is simpler):

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <Windows.h>
#define m 10000
SheelSort_1(int* arr, int n)
{
    
    
    int gap = 3;
        //按顺序,一组一组排序
        for (int i = 0; i < n - gap; i ++)
        {
    
    
            //单趟
            int end = i;
            int tmp = arr[end + gap];
            while (end >= 0)
            {
    
    
                if (arr[end] < tmp)//从大到小排序
                {
    
    
                    arr[end + gap] = arr[end];
                    end -= gap;
                }
                else
                    break;
            }
            arr[end + gap] = tmp;
        }
}
int main()
{
    
    
    int head, tail, i;
    int arr[m] = {
    
    0};
    srand((unsigned)time(NULL));
    
    for (i = 0; i < m; i++)
        arr[i] = rand()%1000;
    head = clock();
    SheelSort_1(arr, sizeof(arr) / sizeof(arr[0]));
    tail = clock();
    printf("%d ", tail - head);

    return 0;
}

Insert image description here
We can know the meaning of pre-sorting:
1. The larger the gap, the larger the number You can get to the back faster, and small numbers can get to the front faster. The larger the gap, the faster it jumps, and the less close it is to order.
2. The smaller the gap, the slower the large and small numbers move, and the closer they are to order.
3. gap= =1, which is direct insertion sorting.
But we don’t know what is the best value for gap
We are changing the code so that no matter how big the gap is, it will eventually equal gap= =1. (gap >1 is pre-sorting)

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <Windows.h>
#define m 10000
SheelSort_3(int* arr, int n)
{
    
    
    int gap = n;
    while(gap >1)//先预排序,预排序结束后,直接插入排序
    {
    
    
    gap=gap/3+1;
    //gap=gap/2;
        //按顺序,一组一组排序
        for (int i = 0; i < n - gap; i ++)
        {
    
    
            //单趟
            int end = i;
            int tmp = arr[end + gap];
            while (end >= 0)
            {
    
    
                if (arr[end] < tmp)//从大到小排序
                {
    
    
                    arr[end + gap] = arr[end];
                    end -= gap;
                }
                else
                    break;
            }
            arr[end + gap] = tmp;
        }
        }
}
int main()
{
    
    
    int head, tail, i;
    int arr[m] = {
    
    0};
    srand((unsigned)time(NULL));
    
    for (i = 0; i < m; i++)
        arr[i] = rand()%1000;
    head = clock();
    SheelSort_3(arr, sizeof(arr) / sizeof(arr[0]));
    tail = clock();
    printf("%d ", tail - head);

    return 0;
}

Calculate its time complexity?

1. When the gap is very large, gap=n / 3+1, it can be divided into n/3 groups of data, each group has 3 elements, and the worst number of comparisons in each group is 3 times, so the total is: n / 3 * 3 times.
2. When the gap is very small, gap=1, each group has 1 element, which is very close to order. For these data with a distance of gap, the number of times the data is moved back: n.
3. When the gap is very large, n / 9 groups, 9 elements, each group has a worst-case comparison of 36 times. (1+2...+8), these data are spaced by gap. Total moving data: n / 9* 36 = 4n times
4. The loop inside operates log3^N times
Summary: Total n / gap groups, each Group gaps, and insert into each group: 1+2+3+……+gap. Total: (1+gap) * gap / 2
Time complexity O(N^1.3) best case

Stability: Unstable

4. Sorting algorithm complexity and stability analysis

as shown:
Insert image description here
subscriptive:
Insert image description here

Guess you like

Origin blog.csdn.net/plj521/article/details/133189139