在数组中按排序顺序添加元素

时间:2017-02-23 16:54:55

标签: c

我希望在以排序方式输入数组时添加元素。这意味着在数组中输入新元素时,它将添加其排序状态。

我尝试过以下示例,但我希望以自动方式执行此操作。有人可以帮帮我吗?

我的例子

#include <stdio.h>
void main()
{
    int a[20], n, item, i;

    printf("Enter the size of the array");
    scanf("%d", &n);

    printf("Enter elements of the array in the sorted order");
    for (i = 0; i<n; i++)
    {
        scanf("%d", &a[i]);
    }

    printf("\nEnter ITEM to be inserted : ");
    scanf("%d", &item);

    i = n - 1;
    while (item<a[i] && i >= 0)
    {
        a[i + 1] = a[i];
        i--;
    }
    a[i + 1] = item;
    n++;

    printf("\n\nAfter insertion array is :\n");
    for (i = 0; i<n; i++)
    {
        printf("\n%d", a[i]);
    }
    getch();
}

0 个答案:

没有答案
相关问题