萌新求助!(关于快速排序)
#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 < median){
i ++;
}
//对右侧的数据判断
while(array > median){
j --;
}
//左侧数据大于右侧数据时交换
if(i <= j)
{
array = temp;
array = array;
array = 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);
quick_sort(array,0,length - 1);
printf("排序后的结果是:");
for(a = 0;a < length;a ++)
{
printf("%d ",array);
}
putchar('\n');
return 0;
}
编译运行后执行结果为:
排序后的结果是:1 12650328 4 5 6 7 0 0 12648448
找了好久,不晓得哪里出错了{:10_269:} 其实整体对是对的,就是一个细节错了
if(i <= j)
{
array = temp;
array = array;
array = temp;
i ++;
j --;
}
这里的temp和array弄反了,应该是
if(i <= j)
{
temp = array;
array = array;
array = 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 < median){
i ++;
}
//对右侧的数据判断
while(array > median){
j --;
}
//左侧数据大于右侧数据时交换
if(i <= j)
{
temp = array;
array = array;
array = 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);
quick_sort(array,0,length - 1);
printf("排序后的结果是:");
for(a = 0;a < length;a ++)
{
printf("%d ",array);
}
putchar('\n');
system("pause");
return 0;
} 小甲鱼的铁粉 发表于 2020-11-22 09:11
其实整体对是对的,就是一个细节错了
这里的temp和array弄反了,应该是
噢噢,谢谢了{:10_257:}
页:
[1]