C language quick sort method

C language quick sort method

Table of contents

What is Quick Sort Algorithm

Quick sort is an efficient sorting algorithm. Its basic idea is to divide a large array into two smaller sub-arrays, all elements in one sub-array are smaller than the elements in the other sub-array, and then recursively sort the two sub-arrays. sub-array. Because it is a divide and conquer algorithm, it is recursive and has high efficiency.

C language implements quick sort

It is also very simple to implement quick sorting in C language. The following is the code for quick sorting in C language:

#include <stdio.h>

void quick_sort(int arr[], int low, int high) {
    
    
    if (low >= high) return;

    int pivot = arr[(low+high)/2];
    int i = low-1, j = high+1;
    while (i < j) {
    
    
        do i++; while (arr[i] < pivot);
        do j--; while (arr[j] > pivot);
        if (i < j) {
    
    
            int tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }
    }

    quick_sort(arr, low, j);
    quick_sort(arr, j+1, high);
}

int main() {
    
    
    int arr[] = {
    
    6, 5, 3, 1, 8, 7, 2, 4};
    int len = sizeof(arr) / sizeof(arr[0]);

    quick_sort(arr, 0, len-1);

    for (int i=0; i<len; i++) {
    
    
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

In the above code, we define a function quick_sort whose parameters are the array arr to be sorted, the starting position low of the sub-array and the end position high of the sub-array. In the function, first judge whether the length of the subarray is less than or equal to 1, and if so, return directly (recursion boundary). Otherwise, we take the element in the middle of the subarray as the pivot point, and use a while loop to divide the subarray into two parts: elements smaller than pivot and elements larger than pivot. We then recursively sort the left and right subarrays.

Time Complexity of Quick Sort

The time complexity of quick sort depends on the depth of recursion and the number of elements in each division. Its average time complexity is O(n*logn), and the worst case time complexity is O(n^2). The worst case here means that the choice of the reference point leads to the worst division situation. In practical applications, the average time complexity of the quick sort algorithm is usually better than other sorting algorithms, so it is widely used.

animation

Here is an animation of quicksort (author: Koshy George):
insert image description here

Guess you like

Origin blog.csdn.net/weixin_46121540/article/details/129780901