我的选择代码-排序
#include <stdio.h>
void selection_sort(int a[], int n);
int main()
{
int size;
printf("Enter the size of array: ");
scanf("%d",&size);
int b[size],i = 0;
printf("Enter %d integers to be sorted: ",size);
while(i++ < size)
scanf("%d",&b[i]);
selection_sort(b, size);
printf("Sorted integers(by selection sort) are: ");
for(int i = 0; i < size; i++)
printf("%d",b[i]);
return 0;
}
void selection_sort(int a[], int n)
{
while(n >= 0 )
{
if(n == 0)
break;
else
{
int i = 0, c = 0;
int largest = a[0];
while(i++ < n)
if(largest < a[i])
{
c = i ;
largest = a[i];
}
int temp = a[--n];
a[n] = largest;
a[c] = temp;
selection_sort(a, n);
}
}
}按升序排序数组
3 4 1 2给出了奇怪的输出
2293388 4 3 0我检查了很多次,但没能解决这个问题。我该怎么做才能正常工作呢?
算法使用:
请不要给出任何其他的解决办法,否则我会糊涂的。
发布于 2013-07-01 17:30:40
编辑
啊,我知道出了什么问题。首先,while (i++ < n)并没有完全按照您的期望来做。它检查条件i < n是否为真,然后递增i。然而,在条件检查之后,i似乎已经在身体中增加了。例如,
while (i++ < n)
printf ("%d ", i);将打印出来(使用n=4):
1 2 3 4所以你首先需要改变这种状况。其次,外部的时间循环是完全没有必要的.使用一个循环就足够了。同样,将这里的while循环更改为while (i < n),并在主体中增加i。最后的代码是:
#include <stdio.h>
void selection_sort(int a[], int n);
int main()
{
int size;
printf("Enter the size of array: ");
scanf("%d", &size);
int b[size], i = 0;
printf("Enter %d integers to be sorted: ", size);
while(i < size) {
scanf("%d", &b[i]);
i++;
}
selection_sort(b, size);
printf("Sorted integers(by selection sort) are: ");
i = 0;
for(i = 0; i < size; i++)
printf("%d ", b[i]);
printf ("\n");
return 0;
}
void selection_sort(int a[], int n)
{
if(n == 0)
return;
else
{
int i = 0, c = 0;
int largest = a[0];
while(i < n) {
if(largest < a[i])
{
c = i;
largest = a[i];
}
i++;
}
int temp = a[--n];
a[n] = a[c];
a[c] = temp;
selection_sort(a, n);
}
}我用给定的输入(3 4 1 2)测试了它,它输出了一个排序列表:1 2 3 4。
发布于 2013-07-01 18:07:06
每当你看到如此奇怪的大数字,它通常是一个数组出界的问题。请拿一个小的数据集,比如说5-6个数字,然后遍历你的程序.我相信你能修好它。祝你好运!
https://stackoverflow.com/questions/17409831
复制相似问题