Data Structure--》Master the sorting algorithm in data structure

        When we face massive data, how to sort it efficiently is an important issue in the field of data structure. As a key part, the sorting algorithm plays a vital role.

        Whether you are a beginner or an advanced person, this article will provide you with simple, easy-to-understand, practical and feasible knowledge points to help you better grasp the importance of sorting algorithms in data structures and algorithms, thereby improving your algorithmic problem-solving capabilities. . Next, let us embark on a wonderful journey of data structures and algorithms.

        When we need to sort a set of data, we need to use a sorting algorithm. Usually, we arrange a set of data according to certain rules to make it easier to find and process.

        Common sorting algorithms includebubble sort, insertion sort, Selection sort, Hill sort, Merge sort, Quick sort and so on. These algorithms have their own advantages and disadvantages, and different algorithms are suitable for different application scenarios. Therefore, selection needs to be made based on specific circumstances in actual development. Next, according to the syllabus requirements of the postgraduate entrance examination, we will focus on explaining the relevant sorting algorithms:

Table of contents

insertion sort

swap sort

selection sort

merge sort

Radix sort


insertion sort

Algorithm idea: Each time a record to be sorted is inserted into the previously sorted subsequence according to its key size, until all records are inserted. The implementation process is roughly as follows:

1) Starting from the first element, consider it a sorted interval.

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

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

4) Repeat step 3 until you find the position where the sorted element is less than or equal to the new element.

5) Insert the new element into the position.

Implement insertion sort algorithm in C language:

void insertionSort(int arr[], int n) {
    int i, key, j;
    for (i = 1; i < n; i++) {
        key = arr[i];
        j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

Reviewing the key points, the main contents are summarized as follows:

Hill sorting: It is a sorting algorithm based on insertion sort, also known as shrinking incremental sorting. It groups the elements to be sorted, then performs insertion sort on the elements of each group in turn, and finally performs insertion sort on the entire sequence. As follows:

The results obtained by performing direct insertion sort on the generated subtable are as follows:

Until d equals 1, the sorting results obtained are basically in order, and then direct insertion sorting is performed to obtain the final result.

The final process results presented are as follows:

Implement Hill sorting algorithm in C language: 

#include <stdio.h>

void shellSort(int arr[], int n) {
    // 定义增量序列
    int gap, i, j, temp;
    for (gap = n / 2; gap > 0; gap /= 2) {
        // 内部使用插入排序对每个子序列进行排序
        for (i = gap; i < n; i++) {
            temp = arr[i];
            j = i;
            while (j >= gap && arr[j - gap] > temp) {
                arr[j] = arr[j - gap];
                j -= gap;
            }
            arr[j] = temp;
        }
    }
}

int main() {
    int arr[] = {9, 5, 2, 7, 1, 8};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("原始数组:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    shellSort(arr, n);
    
    printf("\n排序后数组:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}

Reviewing the key points, the main contents are summarized as follows:

swap sort

Exchange sorting is a relatively simple and intuitive sorting algorithm. Its main idea is to gradually "bubble" the largest or smallest elements to the correct position by exchanging adjacent elements in the array that do not meet the order requirements. . Commonly used exchange sorting algorithms include bubble sort and quick sort, as follows We will focus on explaining the related implementations of these two sorts:

Bubble sorting: The most basic exchange sorting algorithm. Its core idea is to compare adjacent elements in sequence from left to right, and exchange larger elements to the back. The algorithm is repeated multiple times, each time placing an unsorted element in the correct position, until the entire array is sorted. The time complexity of bubble sort is O(n^2).

Compare the before and after values, with the smaller one in front and the larger one in the back, and then repeat several times until the order is sorted from small to large.

Implement bubble sorting algorithm in C language:  

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    int i, j, temp;
    for (i = 0; i < n-1; i++) {
        for (j = 0; j < n-i-1; j++) {
            if (arr[j] > arr[j+1]) {
                // 交换相邻元素
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {9, 5, 2, 7, 1, 8};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("原始数组:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    bubbleSort(arr, n);
    
    printf("\n排序后数组:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}

Reviewing the key points, the main contents are summarized as follows:

Quick sort: It is a sorting algorithm based on the divide-and-conquer idea. It divides the problem into smaller sub-problems and then solves these sub-problems recursively. In quick sort, the records to be sorted are divided into two independent parts through one sorting. The keywords of one part of the record are smaller than the keywords of the other part of the record. Then the two parts of the records are sorted in this way, recursively. Continue until the entire sequence is in order. The average time complexity of quicksort is O(n log n), and the worst-case time complexity is O(n^2).

Implement quick sorting algorithm in C language:   

#include <stdio.h>

// 交换数组中两个元素的值
void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// 将基准元素放在正确的位置,并返回该位置的索引
int partition(int arr[], int low, int high) {
    int pivot = arr[high];  // 将最后一个元素设为基准元素
    int i = (low - 1);  // i 初始化为最低索引的前一个

    for (int j = low; j <= high - 1; j++) {
        if (arr[j] < pivot) {
            i++;  // 找到一个比基准元素小的元素,将 i 向后移动
            swap(&arr[i], &arr[j]);  // 交换 arr[i] 和 arr[j]
        }
    }
    swap(&arr[i + 1], &arr[high]);  // 将基准元素放置在正确的位置

    return (i + 1);
}

// 快速排序函数
void quickSort(int arr[], int low, int high) {
    if (low < high) {
        // 将基准元素放置在正确的位置
        int pi = partition(arr, low, high);

        // 递归调用快速排序函数
        quickSort(arr, low, pi - 1);  // 对基准元素左侧的子数组进行排序
        quickSort(arr, pi + 1, high);  // 对基准元素右侧的子数组进行排序
    }
}

// 打印数组元素
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {9, 5, 2, 7, 1, 8};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("原始数组:");
    printArray(arr, n);

    quickSort(arr, 0, n - 1);

    printf("排序后数组:");
    printArray(arr, n);

    return 0;
}

Reviewing the key points, the main contents are summarized as follows: 

selection sort

Selection sort is a simple and intuitive sorting algorithm. Its basic idea is to select the smallest (or largest) element from the unsorted part each time and then place it at the end of the sorted part. Repeat this process until all elements are sorted. Commonly used exchange sorting algorithms include simple selection sort and heap sort, as follows We will focus on explaining the related implementations of these two sorts:

Simple selection sort: The basic idea is to select the smallest (or largest) element from the unsorted part each time, and then combine it with the first element of the unsorted part Swap the positions, i.e. place the smallest element at the end of the sorted section. Repeat this process until all elements are sorted.

The performance analysis of this algorithm is as follows:

Reviewing the key points, the main contents are summarized as follows:

bank order :

Heap sort is a sorting algorithm based on the heap data structure, which takes advantage of the characteristics of the heap for sorting. Heap is a complete binary tree, divided into two types: max heap and min heap.

For explanations about heap sorting, please refer to my previous article:Unlocking the Mysteries of Trees and Binary Trees in Data Structures (2) Heap in Sorted explanations and summarized knowledge are as follows:

merge sort

Merge sort is a commonly used sorting algorithm based on the idea of ​​divide and conquer. Merge sort continuously divides the array to be sorted into smaller sub-arrays, and then gradually merges these sub-arrays into a large ordered array, and finally obtains a completely ordered array. as follows:

The process of hand-calculated simulated merge sort is as follows:

Reviewing the key points, the main contents are summarized as follows: 

Radix sort

Radix sort is a non-comparative integer sorting algorithm. It divides the integers to be sorted into different number groups according to the number of digits, and then sorts each number group to finally obtain an ordered integer array.

The result obtained is then divided into tens:

The final result is as follows:

Reviewing the key points, the main contents are summarized as follows: 

Guess you like

Origin blog.csdn.net/qq_53123067/article/details/133842753