排序算法(一)——快速排序+插入排序的灵活运用

用C语言如何实现快速排序算法:

快速排序算法一般适合元素较多的情况,代码简洁,节省内存。

但当元素较少的时候,使用插入排序算法更有优势。

所以,本篇代码中,当元素个数小于cutoff时,采用了插入排序算法排列剩下的元素。

#include <stdio.h>
#include <stdlib.h>
#define cutoff 10

void Quick_sort(int A[], int N);
void Quicksort(int A[], int left, int right);
void InsertionSort(int A[], int N);
int median(int A[], int left, int right);
void swap(int *x, int *y);

int main()
{
    int i;
    int A[30] = {34, 34, 21, 432, 234, 231, 11, 111, 123, 13, 56, 45, 34, 13, 56, 45, 34, 24, 12, 134, 12324, 12, 134};

    printf("Before ordering: \n");
    for (i = 0; i < 23; i++)
    {
        printf ("%d ", A[i]);/*print the numbers before sort*/
    }

    Quick_sort(A, 22);/*sort numbers*/

    printf("\n After ordering\n");
    for (i = 0; i < 23; i++)
    {
	printf("%d ", A[i]);/*print the numbers after sort*/
    }
    printf("\n");
    return 0;

}/*end of main*/

void Quick_sort(int A[], int N)
{
    Quicksort(A, 0, 22);
}

void Quicksort(int A[], int left, int right)
{
    int i, j;
    int pivot;

    if (left + cutoff <= right)/*use quick sort when the array is long enough, if not, use insertion sort.*/ 
    {
        pivot = median(A, left, right);
	i = left;
	j = right -1;
	for (; ;)
	{
	    while (A[++i] < pivot){}
	    while (A[--j] > pivot){}
	    if (i < j)
	        swap(&A[i],&A[j]);/*exchange the position of A[i] and A[j].*/ 
	    else
	        break;
	}
	swap(&A[i], &A[right - 1]);

	Quicksort(A, left, i-1);/*call itself to deal with the former numbers of pivot.*/
	Quicksort(A, i + 1, right);/*call itself to deal with the after numbers of pivot.*/ 
    }
    else 
        InsertionSort(A +left, right - left +1);

}/*end of Quicksort*/

void InsertionSort(int A[], int N)
{
	int j, p;
	int temp;
	for (p = 1; p < N; p++)
	{
	    temp = A[p];
	    for (j = p; j > 0 && A[j-1] > temp; j--)
	    {
	        temp = A[p];
		for(j = p; j > 0 && A[j -1] > temp; j--)
		{
		    A[j] = A[j - 1];
		}

		A[j] = temp;
	    }
	}
}

int median(int A[], int left, int right)/*choose the center number of the array to be the pivot.*/
{
    int center = (left + right)/2;

    if (A[left] > A[center]);
        swap(&A[left], &A[center]);
    if (A[left] > A[right]);
        swap(&A[left], &A[right]);
    if (A[center] > A[right]);
        swap(&A[center], &A[right]);

    swap(&A[center], &A[right-1]);/*hide the pivot at the A[right - 1] to simplify the following sort.*/
    return A[right -1];
}

void swap(int *x, int *y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值