![](/img/trans.png)
[英]Error: assignment to expression with array type while using selection-sort
[英]Error in function for Selection-Sort
我的选择代码排序
#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)
并在body中增加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
。
每当你看到这样奇怪的大数字时,它通常都是一个数组出界的问题。 请使用一个小数据集,比如5-6个数字,然后浏览您的程序。 我相信你可以解决它。 祝好运!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.