【发布时间】:2016-05-05 00:01:45
【问题描述】:
我的任务是编写一个函数 naive_sort(),它将随机生成的整数数组作为参数并对它们进行排序。我需要使用插入排序。我已经到了不知道如何解决问题的地步,当我运行程序时没有任何反应。控制台保持空白。我对 C 编程相当陌生,所以如果您在某处发现一个愚蠢的错误,请不要感到惊讶。任何帮助将不胜感激。
编辑:它正在输出一个数字列表,但它们没有被排序,输出示例:
558915997481717626
152655717476818999
这是我的代码(已编辑):
#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
#include <time.h>
//Insertion Sort function to Sort Integer array list
int *naive_sort(int array[],int n)
{
int j,temp,i;
//Iterate start from second element
for (i = 1; i < n; i++)
{
j = i;
//Iterate and compare till it satisfies condition
while ( j > 0 && array[j] < array[j-1])
{
//Swapping operation
temp = array[j];
array[j] = array[j-1];
array[j-1] = temp;
j--;
}
}
//return Sorted array
return array;
}
int main()
{
//declaring variables
int array[10],i;
int n = 10;
srand (time(NULL)); //initialize random seed
for (i=0; i<n; i++)
{
array[i] = rand() % 100;
scanf("%d",&array[i]);
}
for(i=0; i<n; i++)
{
printf("%d", array[i]);
}
printf("\n");
//calling naive_sort function defined above and getting
//sorted array in sortArray variable
naive_sort(array,n);
//print sorted array
for(i = 0; i<n; i++ )
{
printf("%d",array[i]);
}
printf("\n");
return 0;
}
【问题讨论】:
-
主函数中间的
return 0;是有意的吗?在我看来,如果你退出主函数,这个程序永远不会调用 naive_sort ......但你的意思是这个程序根本不输出任何东西吗?连 "arr[0]=X" 部分都没有? -
不是故意的,我忘了。我现在已经修好了,程序正在输出一些东西,但数字没有被排序 =/
标签: c arrays sorting insertion