Quick Sort template (C language)

Quick Sort basic idea:

Quick sort using the idea of ​​partition. Selecting a demarcation point, to be sorted by the sorting trip sequence is divided into two parts, a small portion of the score values ​​of the critical point, a large portion of the boundary score point values. Further recursive sort two parts, so that the entire sequence of ordered last.

Quick sort steps:

  1. Determining the cut-off point. Boundary point may be selected array [left], array [right], array [(left + right) / 2] or a randomly selected element in the sequence;
  2. Adjustment range;
  3. Recursive process around the two sequences.

Quick Sort basic implementation analysis:

Quick sort template code:

void quick_sort(int *arr, int l, int r)
{
    if(l >= r)
        return ;
    int x = arr[l], i = l - 1, j = r + 1;    //选取左边界值为分界点x,创建i,j两个指针,使其分别指向l - 1和r + 1;
    while(i < j)
    {
        do i++; while(arr[i] < x);
        do j--; while(arr[j] > x);
        if(i < j)
            swap(&arr[i], &arr[j]);
    }
    quick_sort(arr, l, j);
    quick_sort(arr, j + 1, r);
}

快速排序完整实现代码:

#include <stdio.h>
#include <stdlib.h>

void swap(int *first, int *second)
{
    int temp = *first;
    *first = *second;
    *second = temp;
}

void quick_sort(int *arr, int l, int r)
{
    if(l >= r)
        return ;
    int x = arr[l], i = l - 1, j = r + 1;
    while(i < j)
    {
        do i++; while(arr[i] < x);
        do j--; while(arr[j] > x);
        if(i < j)
        {
            swap(&arr[i], &arr[j]);
        }
    }
    quick_sort(arr, l, j);
    quick_sort(arr, j + 1, r);
}

int main()
{
    int i;
    int n;
    int *array;
    printf("请输入数组的大小:");
    scanf("%d", &n);
    array = (int*) malloc(sizeof(int) * (n + 1));// 第一个元素 用来保存中间变量 
    printf("请输入数据(用空格分隔):");
    for (i = 0; i <= n - 1; i++)
    {
        scanf("%d", &array[i]);
    }
    quick_sort(array, 0, n - 1);
    printf("排序后为:");
    for (i =  0; i <= n - 1; i++)
    {
        printf("%d ", array[i]);
    }
    printf("\n");
    
}

 

Guess you like

Origin www.cnblogs.com/ChanJL/p/11300939.html