快速排序c语言代码 可直接运行

2种都可直接运行
代码一
#include <stdio.h>
void Quick_Sort(int *arr, int begin, int end){
if(begin > end)
return;
int tmp = arr[begin];
int i = begin;
int j = end;
while(i != j){
while(arr[j] >= tmp && j > i)
j–;
while(arr[i] <= tmp && j > i)
i++;
if(j > i){
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
arr[begin] = arr[i];
arr[i] = tmp;
Quick_Sort(arr, begin, i-1);
Quick_Sort(arr, i+1, end);
}
int main()
{
int i;
int a[] = {5,13,6,24,2,8,19,27,6,12,1,17};
int N = 12;
Quick_Sort(a, 0, 11);
for(i=0; i<N; i++)
printf(“%d “, a[i]);
printf(”\n”);

return 0;

}

代码二
#include <stdio.h>

void swap(int a[], int low, int high) //交换两个数的值
{
int t = a[low];
a[low] = a[high];
a[high] = t;
}

int partition(int a[], int low, int high) //计算基准点,分割为左右两个数组
{
int point = a[low];//基准点等于第一个元素
/* while(1){
while(low<high && a[++low]<point);
while(a[–high]>point);
if(low>=high) break;
*/
while(low<high)
{
while(low<high && a[high]>=point)//控制high指针比较并左移
{
high–;
}
swap(a,low,high);
//}
while(low<high && a[low]<=point)//控制low指针比较并右移
{
low++;
}
swap(a,low,high);
}
return low;//返回基准点位置
}

void quicksort(int a[], int low, int high) //low:起始位置 high:末尾位置
{
if(low<high){
int point = partition(a,low,high);//计算基准点
quicksort(a,low,point-1); //对基准点的左边进行排序
quicksort(a,point+1,high);//对基准点的右边进行排序
}
}

int main()
{
int i;
int a[] = {5,13,6,24,2,8,19,27,6,12,1,17};
int N = 12;

quicksort(a, 0, N-1);

for(i=0; i<N; i++) printf("%d ", a[i]);
printf("\n");

return 0;

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值