关于选择排序的问题
/* 使用选择排序给输入的数据排序 */#include<stdio.h>
#define N 3
void selectionSort(int a[],int);
int main(void)
{
int a;
int i;
printf("Enter %d numbers to be sorted:",N);
for(i = 0; i < N; i++)
{
scanf("%d",&a);
}
selectionSort(a,N);
printf("In order:\n");
for(i = 0; i < N; i++)
{
printf("%d ",a);
}
printf("\n");
return 0;
}
void selectionSort(int a[],int n)
{
int temp;
int max = 0;
int index;
int i;
while(n >= 2)
{
for(i = 0; i < n; i++)
{
if(a > max)
{
max = a;
index = i;
}
}
n--;
if(index != n)
{
temp = a;
a = a;
a = temp;
}
selectionSort(a,n);
}
}
请问哪里错了,问什么不能正确地排序? index应该不会等于i n 是这样的,你的max=0,所以你的任何输入都会大于0,也就是说a肯定大于0,所以index也等于0,然后n--,当n=1的时候你的while语句就不成立了,结束循环,退出函数,返回到主函数。你想想是不是这样。 额……看错了 楼主试试把max设置全局变量试试 。选择排序不至于用递归吧。如果用递归就不要用那个while循环了。
你用了递归。然后又进行了一次循环。把本来排好的可能又会打乱。
页:
[1]