Algorithm Design and Analysis - Ten Classic Sorting Algorithms 1 (1--5)

Table of contents

Algorithm Design and Analysis - Ten Classic Sorting Algorithms

Level 1: Bubble Sort

 Reference Code

Level 2: Selection Sort

Reference Code

Level 3: Insertion sort

 Reference Code

Level 4: Hill Sort

Reference Code

Level 5: Merge Sort

 Reference Code

The author has something to say


An unknown college student, known as Caigou by Jiang Hu
original author: jacky Li
Email : [email protected]

 Time of completion:2023.2.28
Last edited: 2023.2.28

Guide:

Help beginners in algorithm design to quickly grasp algorithm design, and help Jing Jing to sort the importance of ABCD... etc. more clearly!

Algorithm Design and Analysis - Ten Classic Sorting Algorithms

Level 1: Bubble Sort

mission details

The task of this level: implement the bubble sort algorithm and change the random sequence into ascending order.

related information

In order to complete the task of this level, you need to master: 1. Bubble sort algorithm.

Bubble Sort Algorithm

Bubble sort repeatedly traverses the array to be sorted, comparing two adjacent elements each time, and swapping them if they are in the wrong order. Repeated traversal until there is no need to exchange, it means that the sequence has been sorted.

  • Algorithm steps:

    1. Compare adjacent elements: if the first is greater than the second, exchange;

    2. Traverse the first pair from the beginning to the last pair at the end, and execute the steps 1;

    3. Repeat steps 1~ 2until sorting is complete.

  • Bubble sorting can be improved: after the first sorting, the last element is the largest, so the next traversal only needs to be executed to the penultimate pair.

programming requirements

The programming task of this level is to complete the code sort_arrayfrom the middle Beginto the middle of the code snippet on the right. The specific requirements are as follows:End

  • In sort_array, the bubble sort algorithm is implemented to complete the specified output.

Test instruction

The platform will automatically compile the completed code, generate several sets of test data, and then judge whether the program is correct based on the output of the program.

The following is a test sample of the platform:

Test input:

10

7 1 4 6 8 9 5 2 3 10

Expected output:

1 4 6 7 8 5 2 3 9 10

1 4 6 7 5 2 3 8 9 10

1 4 6 5 2 3 7 8 9 10

1 2 3 4 5 6 7 8 9 10

Test input:

15

3 44 38 5 47 15 36 26 27 2 46 4 19 50 48

Expected output:

3 38 5 44 15 36 26 27 2 46 4 19 47 48 50

3 5 38 15 36 26 27 2 44 4 19 46 47 48 50

3 5 15 36 26 27 2 38 4 19 44 46 47 48 50

2 3 4 5 15 19 26 27 36 38 44 46 47 48 50

 Reference Code

#include "sort_.h"
 
void print_array(int *arr, int n)
{
    if(n==0){
        printf("ERROR: Array length is ZERO\n");
        return;
    }
    printf("%d", arr[0]);
    for (int i=1; i<n; i++) {
        printf(" %d", arr[i]);
    }
    printf("\n");
}
 
void sort_array(int *arr, int n)
{
    int i, x, j;
    for(j = 0; j < n; j ++)
    {
        for(i = 0; i < n - 1; i ++)
        {
            if(arr[i] > arr[i + 1]) 
            {
                x = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = x;
            }
        }
        if(j < 3) print_array(arr, n);
    }
    print_array(arr, n);
}

Level 2: Selection Sort

mission details

The task of this level: implement the selection sorting algorithm and change the random sequence into ascending order.

related information

In order to complete the task of this level, you need to master: 1. Selection sorting algorithm.

selection sort algorithm

Selection sorting is a simple and intuitive sorting algorithm. First find the smallest element in the unsorted sequence, store it at the beginning of the sorted sequence, and then continue to find the smallest element from the remaining unsorted elements, and then put it in the sorted sequence end of . And so on until all elements are sorted.

  • Algorithm steps:

    1. Initial state: the unordered sequence is R[0,n−1], the length is n, and the ordered area is empty;

    2. The i=1,..,n−1 sorting selects the smallest element R[k] from the current unordered area R[i−1,n−1], and combines it with the first element in the unordered area Record R[i−1] exchange, then R[0,i−1] becomes a new ordered area with the number of elements increased by 1, and R[i,n−1] becomes a new disordered area with the number of elements reduced by 1 district;

    3. End after n−1 rounds of selection swaps.

programming requirements

The programming task of this level is to complete the code sort_arrayfrom the middle Beginto the middle of the code snippet on the right. The specific requirements are as follows:End

  • In sort_array, implement the selection sorting algorithm and complete the specified output.

Test instruction

The platform will automatically compile the completed code, generate several sets of test data, and then judge whether the program is correct based on the output of the program.

The following is a test sample of the platform:

Test input:

10

7 1 4 6 8 9 5 2 3 10

Expected output:

1 7 4 6 8 9 5 2 3 10

1 2 4 6 8 9 5 7 3 10

1 2 3 6 8 9 5 7 4 10

1 2 3 4 5 6 7 8 9 10 

Test input:

15

3 44 38 5 47 15 36 26 27 2 46 4 19 50 48

Expected output:

2 44 38 5 47 15 36 26 27 3 46 4 19 50 48

2 3 38 5 47 15 36 26 27 44 46 4 19 50 48

2 3 4 5 47 15 36 26 27 44 46 38 19 50 48

2 3 4 5 15 19 26 27 36 38 44 46 47 48 50

Reference Code

#include "sort_.h"

void print_array(int *arr, int n)
{
    if(n==0){
        printf("ERROR: Array length is ZERO\n");
        return;
    }
    printf("%d", arr[0]);
    for (int i=1; i<n; i++) {
        printf(" %d", arr[i]);
    }
    printf("\n");
}

void sort_array(int *arr, int n)
{
    int len = n;
    int minIndex, temp;
    for (int i = 0; i < len - 1; i++) 
    {
        minIndex = i;
        for (int j = i + 1; j < len; j++) 
            if (arr[j] < arr[minIndex]) 
                minIndex = j;

        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
        if (i < 3) print_array(arr, n);
    }
    print_array(arr, n);
}

Level 3: Insertion sort

mission details

The task of this level: implement the insertion sort algorithm and change the random sequence into ascending order.

related information

In order to complete the task of this level, you need to master: 1. Insertion sort algorithm.

insertion sort algorithm

The working principle of insertion sorting is to construct an ordered sequence. For unsorted data, scan from the back to the front in the sorted sequence, find the corresponding position and insert it.

  • Algorithm steps:

    1. Starting from the first element, the element is considered to be sorted;

    2. Take the next element and scan from back to front in the sorted element sequence;

    3. If the sorted element is larger than the new element, move the sorted element to the next position;

    4. Repeat steps 3until you find a position where the sorted element is less than or equal to the new element;

    5. After inserting a new element at that position;

    6. Repeat step 2~ 5.

programming requirements

The programming task of this level is to complete the code sort_arrayfrom the middle Beginto the middle of the code snippet on the right. The specific requirements are as follows:End

  • In sort_array, the insertion sort algorithm is implemented to complete the specified output.

Test instruction

The platform will automatically compile the completed code, generate several sets of test data, and then judge whether the program is correct based on the output of the program.

The following is a test sample of the platform:

Test input:

10

7 1 4 6 8 9 5 2 3 10

Expected output:

1 7 4 6 8 9 5 2 3 10

1 4 7 6 8 9 5 2 3 10

1 4 6 7 8 9 5 2 3 10

1 2 3 4 5 6 7 8 9 10

Test input:

15

3 44 38 5 47 15 36 26 27 2 46 4 19 50 48

Expected output:

3 44 38 5 47 15 36 26 27 2 46 4 19 50 48

3 38 44 5 47 15 36 26 27 2 46 4 19 50 48

3 5 38 44 47 15 36 26 27 2 46 4 19 50 48

2 3 4 5 15 19 26 27 36 38 44 46 47 48 50

 Reference Code

#include "sort_.h"

void print_array(int *arr, int n)
{
    if(n==0){
        printf("ERROR: Array length is ZERO\n");
        return;
    }
    printf("%d", arr[0]);
    for (int i=1; i<n; i++) {
        printf(" %d", arr[i]);
    }
    printf("\n");
}

void sort_array(int *arr, int n)
{
    int i, j, temp;
    for(i = 0; i < n - 1; i ++)
    {
        temp = arr[i + 1];
        j = i;
        while(j > -1 && temp < arr[j])
            arr[j + 1] = arr[j], j --;
        arr[j + 1] = temp;
        if (i < 3) print_array(arr, n);
    }
    print_array(arr, n);
}

Level 4: Hill Sort

mission details

The task of this level: implement the Hill sorting algorithm and change the random sequence into ascending order.

related information

In order to complete the task of this level, you need to master: 1. Hill sorting algorithm.

Hill sort algorithm

Hill sorting was invented by Shell in 1959. It is also called shrinking incremental sorting. It is the first sorting algorithm that breaks through O(n2). It is an improved version of simple insertion sorting and compares elements farther away first.

  • Algorithm steps:

    1. Select an incremental sequence T1​, T2​, ... , Tk​, where Ti​>Tj​, Tk​=1, i>j;

    2. For each sorting, according to the corresponding increment Ti​, the sequence to be sorted is divided into several subsequences, and each subsequence is directly inserted and sorted;

    3. According to the incremental sequence number k, the sequence is sorted k times.

  • Example of Hill sorting: The incremental sequence in the figure below is: 5, 2, 1, the first sorting pass 5inserts the subsequence with an increment of , the second sorting inserts the 2subsequence with an increment of , and the third pass inserts the subsequence with an increment of 1Insertion sorting is performed on the subsequences whose increment is , and finally the sorting is completed.

  • The core of Hill sorting lies in the setting of incremental sequence:

    The incremental sequence can be set in advance, or dynamically defined. For example, if the sequence length is n, then the dynamic increment is: 1, 4, 7, ..., 3x+1<n/3.

programming requirements

The programming task of this level is to complete the code sort_arrayfrom the middle Beginto the middle of the code snippet on the right. The specific requirements are as follows:End

  • In , the Hill sorting algorithm is implemented sort_arrayusing incremental sequences to complete the specified output.[5, 2, 1]

Test instruction

The platform will automatically compile the completed code, generate several sets of test data, and then judge whether the program is correct based on the output of the program.

The following is a test sample of the platform:

Test input:

8

6 10 5 2 4 9 1 7

Expected output:

6 1 5 2 4 9 10 7

4 1 5 2 6 7 10 9

1 2 4 5 6 7 9 10

1 2 4 5 6 7 9 10

Test input:

10

7 1 4 6 8 9 5 2 3 10

Expected output:

7 1 2 3 8 9 5 4 6 10

2 1 5 3 6 4 7 9 8 10

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9 10

Reference Code

#include "sort_.h"

void print_array(int *arr, int n)
{
    if(n==0){
        printf("ERROR: Array length is ZERO\n");
        return;
    }
    printf("%d", arr[0]);
    for (int i=1; i<n; i++) {
        printf(" %d", arr[i]);
    }
    printf("\n");
}

void sort_array(int *arr, int n)
{
    int i, j, m = 0;
    for(int gap = 5; gap > 0; gap /= 2) 
    {
        for(i = gap; i < n; i++) 
        {
            int num = arr[i];
            for(j = i - gap; j >= 0 && arr[j] > num; j -= gap)
                arr[j + gap] = arr[j];
            arr[j + gap] = num;
        }
        if(m < 3)
        {
            print_array(arr, n);
            m ++;
        }
    }
    print_array(arr,  n);
}

Level 5: Merge Sort

mission details

The task of this level: implement the merge sort algorithm, and change the random sequence into ascending order.

related information

In order to complete the task of this level, you need to master: 1. Merge sort algorithm.

Merge Sort Algorithm

Merge sort (MERGE-SORT) is a sorting method implemented using the idea of ​​merging, and is Divide and Conquera very typical application of the divide and conquer method. 分Divide: Divide the problem into some small problems and solve them recursively; 治Conquer: Combine the answers obtained in the divided stages.

  • Algorithm steps:

    1. Divide an input sequence of length n into two subsequences of length n/2;

    2. Use merge sort for the two subsequences respectively;

    3. Merges two sorted subsequences into a final sorted sequence.

programming requirements

The programming task of this level is to complete the code snippet on the right merge_arrayand the code merge_sortfrom the middle Beginto the middle. The specific requirements are as follows:End

  • In merge_array, implement two sorted arrays arr1and arr2merge.
  • In merge_sort, Implementing Merge Sort: A Top-Down Recursive Approach.

Test instruction

The platform will automatically compile the completed code, generate several sets of test data, and then judge whether the program is correct based on the output of the program.

The following is a test sample of the platform:

Test input:

10

7 1 4 6 8 9 5 2 3 10

Expected output:

1 2 3 4 5 6 7 8 9 10

Test input:

15

3 44 38 5 47 15 36 26 27 2 46 4 19 50 48

Expected output:

2 3 4 5 15 19 26 27 36 38 44 46 47 48 50

 Reference Code

#include "sort_.h"

void print_array(int *arr, int n)
{
    if(n==0){
        printf("ERROR: Array length is ZERO\n");
        return;
    }
    printf("%d", arr[0]);
    for (int i=1; i<n; i++)
        printf(" %d", arr[i]);
    printf("\n");
}

int* merge_array(int *arr1, int n1, int* arr2, int n2)
{
    int* res;
    res = new int[n1 + n2];
    int a1 = 0, a2 = 0, index = 0;
 
    for (int i = 0; i < n1+n2; i++) 
        if (i < n1) res[i] = arr1[i];
        else res[i] = arr2[i - n1];

    sort(res, res + n1 + n2);
    return res;
}

int* merge_sort(int *arr, int n)
{
    int mid = n / 2;
    if (mid > 0) 
    {
        int* arr1 = new int[mid];
        int n1 = mid, n2 = n - mid;
        int* arr2 = new int[n2];
        for (int i = 0; i < n; i++) 
            if (i < mid) arr1[i] = arr[i];
            else arr2[i - mid] = arr[i];
 
        merge_sort(arr1, n1);   
        merge_sort(arr2, n - mid);     
        merge_array(arr1, n1, arr2, n2);
    }
    else return  merge_array(arr, n, NULL, 0);
}

The author has something to say

If you feel that what the blogger said is useful to you, please click to support it, and will continue to update such issues...

Guess you like

Origin blog.csdn.net/weixin_62075168/article/details/129260598