C语言 快速排序

快速排序的基本思想:通过一次排序将待排记录分割成独立的两部分,其中一部分记录关键字均比另一部分记录的关键字小,则可以分别对这两部分记录继续进行排序,以达到整个序列有序的目的

#include<stdio.h>

void swap(int k[],int low,int high)
{
	int tmp;
	tmp = k[low];
	k[low] = k[high];
	k[high] = tmp;
}
int Partition(int k[],int low,int high)
{
	int point;
	point = k[low];
	while(low<high)
	{
		while(low < high && k[high]>=point)
		{
			high--;
		}
		swap(k,low,high);
		while(low<high && k[low] <= point)
		{
			low++;
		}
		swap(k,low,high);
	}
}

void QSort(int k[],int low,int high)
{
	int point;
	if(low < high)	
	{
		point = Partition(k,low,high);
		QSort(k,low,point-1);
		QSort(k,point + 1,high);
	}
}

void QuickSort(int k[],int n)
{
	QSort(k,0,n-1);
	
}

int main()
{
	int i,a[10]={5,2,6,0,3,9,1,7,4,8};
	QuickSort(a,10);
	
	for(i = 0;i<10;i++)
		printf("%d",a[i]);

	printf("\n\n");
	return 0;
}

另外一种方法
参考链接



#include <stdio.h>

void quick_sort( int *a, int n)
{
    int i, j, p, tmp;
    if (n < 2)  return;

    p = a[n / 2];   // Get the middle element as pivot ..

    for ( i = 0, j = n -1;; i++, j--) {
        while (a[i] < p)
            i++;
        while (p < a[j])
            j--;
        if ( i >= j)
            break;
        tmp = a[i]; a[i] = a[j]; a[j] = tmp;    //swap both ..
    }   

    quick_sort( a, i); 
    quick_sort( a + i, n - i); 
}


int main(void)
{
    int a[] = { 2, 5, 7, 3, -1, 1, 4}; 
    int n = sizeof a /sizeof a[0];
    int i;
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n -1 ? "\n" : " ");
    quick_sort(a, n); 
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n -1 ? "\n" : " ");
    
    return 0;
}

p取数组中间值,还可以优化。
三数取中或者九数取中。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为了维护世界和平_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值