【发布时间】:2014-12-27 08:25:55
【问题描述】:
编写一个程序,输入一系列整数(存储在数组中),然后通过调用函数 selection_sort 对整数进行排序。当给定一个包含 n 个元素的数组时, selection_sort 必须执行以下操作: 1.搜索数组找到最大的,然后将其移动到最后一个位置。 2.递归调用自身对数组的前n-1个元素进行排序。
以下是我的代码,我认为代码到处都是错误,希望高手可以帮助我
#include <stdio.h>
int selection_sort(int a[])//this function have error that "i"and"count"is undeclared
{
int max = 0;
for (i = 1; i <= count; i++)// continuous compare to final
{
if (a[i] > max)
{
max=a[i];
}
}
a[count] = a[i]; //put the max to last position
count--;
}
int main(void)
{
int a[100] = { 0 },i=0,count=0;
while (1)
{
scanf("%d",&a[i]);
if (a[i] = '\n') { break; }//this line have error because '\n' not "int" so when i "enter" it would not break
i++;
count++; //counting how many integer i scanf
}
selection_sort();//call this function (i don't know well about function so i don't known where to put is correct )
return 0;
}
【问题讨论】:
-
您的代码有语法错误。
selection_sort如何看到count?此外,您的逻辑a[i] == '\n' )有缺陷。a[i]永远不会是'\n'。此外,您正在使用selection_sort中的起始索引1访问数组。那必须是0。 -
codeSmellHomework++; // 咧嘴一笑