在不影响顺序的情况下将数字添加到已排序的降序数组(C)

时间:2018-01-21 23:58:49

标签: c arrays sorting insert

所以在这里我填充数组并生成排序。我需要将键盘输入的数字插入到数组中而不会降低其顺序。请告诉我,我该怎么做。

#include <stdio.h>

int main(void)
{
    //Creating array
    int a[5];
    int i, j, temp;

    printf("Enter number to create array\n");
    for (i = 0; i < 5; i++)
        scanf("%d", &a[i]);

    //Sorting the array ascending descending
    for (i = 1; i < 5; i++) {
        temp = a[i];
        for (j = i - 1; j >= 0; j--)
            if (temp > a[j]) {
                a[j + 1] = a[j];
              a[j] = temp;
            }
    }
    //Output of sorted array
    for (i = 0; i < 5; i++)
        printf("%d\n", a[i]);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

一旦定义了数组的大小,它就会被修复。如果要向其中添加元素,则需要使用增加的大小定义另一个数组。如果要维护排序顺序,则必须将现有元素与新元素进行比较。

#include <stdio.h>

int main(void)
{
  //Creating array
  int a[5];
  int i, j, temp;
  int extra;

  printf("Enter number to create array\n");
  for (i = 0; i < 5; i++)
    scanf("%d", &a[i]);

  //Sorting the array ascending descending
  for (i = 1; i < 5; i++) {
    temp = a[i];
    for (j = i - 1; j >= 0; j--)
      if (temp > a[j]) {
        a[j + 1] = a[j];
        a[j] = temp;
      }
  }

  //Output of sorted array
  for (i = 0; i < 5; i++)
    printf("%d\n", a[i]);

  puts("Enter another number to add");
  scanf("%d", &extra);

  /* Define a larger array to hold the extra element. Naturally, you can
     extend this to use a variable value from user input. */
  int b[6];
  j = 0;
  for (i = 0; i < 5; i++) {
    if (extra > a[i]) {

      /* insert the extra number in the proper order */
      b[j++] = extra;
      b[j++] = a[i];

      /* You have to have a way to stop further comparisons once an
         insertion point is reached. In this case, it's a simple
         expedient of setting the value to zero. Many times a boolean
         flag is used for this purpose. Using zero for this assumes
         that you're only sorting positive integers. */
      extra = 0;
    }
    else {

      /* otherwise, just copy over the sorted elements */
      b[j++] = a[i];
    }
  }
  for (i = 0; i < 6; i++)
    printf("%d\n", b[i]);

  return 0;
}

如果你使用堆分配的整数数组,你可以使用realloc()来调整它的大小,然后找到你的插入点,像你对排序一样使用你的临时变量,然后洗掉其余的数组元素减1。