0

I want to add the element in an array while entering it in a sorted manner. That means at the time of entering the new element in array, it will add its sorted state.

I have tried following examples, but I want to do it in an automatic manner. Can anyone help me, please?

my example

#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();
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • Please tag your post appropriatly, this looks like C syntax, not Basic – Brad Feb 23 '17 at 16:58
  • Thanks Brad for reply, yes i am doing simple assignment in C. – rishikesh magdum Feb 23 '17 at 17:02
  • Looks like you want [std::set](http://www.cplusplus.com/reference/set/set/) or you can roll your own implementation as [suggested here](http://stackoverflow.com/questions/20222891/insert-into-sorted-array) – Brad Feb 23 '17 at 17:03
  • 1
    he's asking you to remove the "basic" tag, basic is a completely separate programming language from C. @Brad The post isn't tagged C++ :/ and looking at the code, I doubt `std::set` is an option. – George Feb 23 '17 at 17:05
  • Sure, I posted my comment before the tag change to `C` only. Have posted a potential solution now – Brad Feb 23 '17 at 17:13
  • The code you've posted works, so if it doesn't solve your problem then I guess I don't understand what you mean by an "automatic manner". – John Bollinger Feb 23 '17 at 17:15
  • Thanks all, i got the solution, @john automatic manner means i mean to say, it has to be inserted in sorted array order before putting in array, i.e check the position and put it in. – rishikesh magdum Feb 23 '17 at 17:21

0 Answers0