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();
}
7
  • Please tag your post appropriatly, this looks like C syntax, not Basic Commented Feb 23, 2017 at 16:58
  • Thanks Brad for reply, yes i am doing simple assignment in C. Commented Feb 23, 2017 at 17:02
  • Looks like you want std::set or you can roll your own implementation as suggested here Commented Feb 23, 2017 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. Commented Feb 23, 2017 at 17:05
  • Sure, I posted my comment before the tag change to C only. Have posted a potential solution now Commented Feb 23, 2017 at 17:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.