C中的插入排序

时间:2015-12-13 18:23:56

标签: c sorting insertion-sort

有人可以帮帮我吗?我必须在C中创建一个Insertion排序代码,用于排序10,20,50,....数字,我必须使用随机数生成器rand()。我想它真的很长时间,仍然无法得到它。我找到了一些可以选择数字的代码。抱歉我的英语不好。

    #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;

}

1 个答案:

答案 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;
}