user6219654 user6219654 - 24 days ago 8
C Question

Sorting an array meanwhile entering values

i need to sort the array while entering values that means that while the user enters numbers the array needs to sort itself: what i did so far is this:

void MoveRight(int *a,int n, int startIndex)
{
int j,temp;
j=n-1;
for(int i=startIndex;i<n;i++)
{
temp = a[j];
a[j]=a[i];
a[i]=temp;
}
}

void InsertionSort(int *a,int n)
{
int i,number,j;
printf("Enter %d numbers for the array\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&number);
for(j=0;j<=i;j++)
{
if(number<a[j])
{
MoveRight(a,n,j);
a[j]=number;
break;
}
}
}
}


After entering: 1,3,2,4,5

The array i got was : -858993460,-858993460,-858993460,-858993460,-858993460

Answer

To apply the selection sort you should at first to enter all elements in the array.

These loops

for(i=0;i<n;i++)
{
    scanf("%d",&number);
    for(j=0;j<=i;j++)
    {
        if(number<a[j])
        {
            MoveRight(a,n,j);
            a[j]=number;
            break;
        }
    }
}

already result in undefined behavior because when i and j are equal to 0 then a[j] has indeterminate value. And moreover if the condition number<a[j] is not evaluated to true then nothing will be added to the array.

Function MoveRight does not make sense because in the loop variable j is not changed.

j=n-1;
for(int i=startIndex;i<n;i++)
{
        temp = a[j];
        a[j]=a[i];
        a[i]=temp;
}

Here is a demonstrative program that shows how the task can be done.

#include <stdio.h>

void MoveRight( int *a, int n, int i )
{
    for ( ; n != i; --n ) a[n] = a[n-1];
}

#define N   10

int main(void) 
{
    int a[N];

    printf( "Enter %d numbers for the array: ", N );

    for ( int i = 0; i < N; i++ )
    {
        int value;

        scanf( "%d", &value );

        int j = 0;
        while ( j < i && !( value < a[j] ) ) j++;

        MoveRight( a, i, j );
        a[j] = value;
    }

    for ( int i = 0; i < N; i++ ) printf( "%d ", a[i] );
    printf( "\n" );

    return 0;
}

The program output might look the following way

Enter 10 numbers for the array: 5 2 3 9 8 1 6 7 4 0
0 1 2 3 4 5 6 7 8 9 

Take into account that for large arrays it is much better to use the binary search instead of the sequential search to find the position where to insert the next value.