Tick-Tack
Tick-Tack

Reputation: 213

Adding a number to a sorted descending array without disturbing the order (C)

So here I fill the array and produce sorting. I need to insert the number entered from the keyboard into the array without knocking down its order. Tell me please how i can do it.

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

Upvotes: 0

Views: 1014

Answers (1)

Mark Benningfield
Mark Benningfield

Reputation: 2892

An array's size is fixed once it's defined. You need to define another array with the increased size if you want to add elements to it. If you want to maintain sort order, you have to compare your existing elements with the new one.

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

If you were using a heap-allocated array of integers, you could use realloc() to resize it, and then find your insertion point, use your temp variable like you did with the sort, and shuffle the rest of the array elements down by 1.

Upvotes: 1

Related Questions