我的选择排序代码
#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
我检查了很多次,但未能解决问题。
我应该怎么做才能正常工作?
使用的算法:
1. 寻找数组中最大的元素。
2. 将最大的元素移动到数组的最后一个位置。
3.递归调用自身对数组的第n -1个元素进行排序。
请不要给出任何其他解决方案,否则我会感到困惑。
最佳答案
编辑
啊,我知道出了什么问题。首先,while (i++ < n)
不完全按照您的期望去做。它检查条件是否 i < n
为真,则递增 i
.但是,似乎在条件检查之后,i
体内已经递增。例如,
while (i++ < n)
printf ("%d ", i);
将打印出来(使用 n=4
):
1 2 3 4
所以你首先需要改变它。其次,根本不需要外部 while 循环。使用一个循环就足够了。同样,将此处的 while 循环更改为 while (i < n)
并增加 i
在 body 里。所以最终代码将是:
#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
.
关于c - 选择排序功能错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17409831/