【发布时间】:2013-07-01 17:01:19
【问题描述】:
我的选择排序代码
#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 个元素进行排序。
请不要给出任何其他解决方案,否则我会感到困惑。
【问题讨论】:
-
您期望的输出是什么?您收到的输出有什么奇怪的地方?还有足够的代码来查看您如何调用该函数会有所帮助。如果
n是数组的大小,那么访问a[n]是未定义的行为。 -
@ShafikYaghmour 好的,让我编辑
-
你是如何“检查这个”的?使用调试器单步执行会告诉您正在使用的索引存在一些问题(例如,代码似乎从未检查过
a[1]和largest)。即使您由于某种原因不能使用调试器,也会有一对printf()转储感兴趣的值(例如largest、i、c、n和数组值)在每个step 会很快告诉你出了什么问题。 -
@MichaelBurr;现在它给
4 3 0 1。
标签: c arrays function sorting data-structures