#include <stdio.h>
int main()
{
int myarray[10];
int i, j, n, temp;
/* Get number of elements in the array */
printf("Enter number of elements in the array \n");
scanf("%d", &n);
/* Read elements of the array */
printf("Enter the array elements \n");
for (i = 0; i < n; i++)
scanf("%d", &myarray[i]);
/* Sort elements of the array */
for (i = 1; i < n; i++) {
j = i;
while ((j > 0) && (myarray[j - 1] > myarray[j])) {
temp = myarray[j - 1];
myarray[j - 1] = myarray[j];
myarray[j] = temp;
j--;
}
}
/* Print the sorted array */
printf("Sorted Array\n");
for (i = 0; i < n; i++)
printf("%d \n", myarray[i]);
return 0;
}
答案 0 :(得分:0)
如果您想使用随机数生成器而不是从键盘输入,请添加一些库标题,并替换输入我评论的数字的三行代码。我还添加了一行防止数组溢出。
#include <stdio.h>
#include <stdlib.h> // added library header
#include <time.h> // added library header
int main()
{
int myarray[10];
int i, j, n, temp;
/* Get number of elements in the array */
printf("Enter number of elements in the array \n");
scanf("%d", &n);
if(n < 1 || n > 10) // check range of elements
exit(1);
/* Read elements of the array */
srand((unsigned)(time(NULL))); // seed the random generator
for (i = 0; i < n; i++) // each element
myarray[i] = rand(); // assign a random number
/* Sort elements of the array */
for (i = 1; i < n; i++) {
j = i;
while ((j > 0) && (myarray[j - 1] > myarray[j])) {
temp = myarray[j - 1];
myarray[j - 1] = myarray[j];
myarray[j] = temp;
j--;
}
}
/* Print the sorted array */
printf("Sorted Array\n");
for (i = 0; i < n; i++)
printf("%d \n", myarray[i]);
return 0;
}