|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
void quick_sort(int array[],int left,int right);
void quick_sort(int array[],int left,int right)
{
int temp;
int i = left,j = right;
int median;
median = array[(right + left)/2];
while(i <= j)
{
//对左侧的数据判断
while(array[i] < median){
i ++;
}
//对右侧的数据判断
while(array[j] > median){
j --;
}
//左侧数据大于右侧数据时交换
if(i <= j)
{
array[i] = temp;
array[i] = array[j];
array[j] = temp;
i ++;
j --;
}
}
//递归
if(i < right)
{
quick_sort(array,i,right);
}
if(j > left)
{
quick_sort(array,left,j);
}
}
int main(void)
{
int array[] = {1,3,5,7,4,5,6,7,8};
int a ,length;
length = sizeof(array) / sizeof(array[0]);
quick_sort(array,0,length - 1);
printf("排序后的结果是:");
for(a = 0;a < length;a ++)
{
printf("%d ",array[a]);
}
putchar('\n');
return 0;
}
编译运行后执行结果为:
排序后的结果是:1 12650328 4 5 6 7 0 0 12648448
找了好久,不晓得哪里出错了
其实整体对是对的,就是一个细节错了 if(i <= j)
{
array[i] = temp;
array[i] = array[j];
array[j] = temp;
i ++;
j --;
}
这里的temp和array[i]弄反了,应该是 if(i <= j)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
i ++;
j --;
}
完整代码 #include <stdio.h>
#include<stdlib.h>
void quick_sort(int array[],int left,int right);
void quick_sort(int array[],int left,int right)
{
int temp;
int i = left,j = right;
int median;
median = array[(right + left)/2];
while(i <= j)
{
//对左侧的数据判断
while(array[i] < median){
i ++;
}
//对右侧的数据判断
while(array[j] > median){
j --;
}
//左侧数据大于右侧数据时交换
if(i <= j)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
i ++;
j --;
}
}
//递归
if(i < right)
{
quick_sort(array,i,right);
}
if(j > left)
{
quick_sort(array,left,j);
}
}
int main(void)
{
int array[] = {1,3,5,7,4,5,6,7,8};
int a ,length;
length = sizeof(array) / sizeof(array[0]);
quick_sort(array,0,length - 1);
printf("排序后的结果是:");
for(a = 0;a < length;a ++)
{
printf("%d ",array[a]);
}
putchar('\n');
system("pause");
return 0;
}
|
|