0

Given an array, I was asked to sort it in a way so that the smallest values is first the, largest value second, the second smallest value third and so on. However when I input the values I do not get the required output.

Advise is appreciated as I have an exam today.

#include<stdio.h>
int main()

{
    int i,j,k,a[6],temp,min;
    for(i=0;i<6;i++)
    scanf("%d",&a[i]);

    for(j=0;j<6;j++)
    {
        if(j%2==0)
        {
            min=a[j];
            for(k=j;k<6;k++)
            {
                if(a[k++]<min)
                min=a[k++];
            }

            temp=a[j];
            a[j]=min;
            min=temp;
        }
        else
        {
            min=a[j];
            for(k=j;k<6;k++)
            {
                if(a[k++]>min)
                min=a[k++];
            }

            temp=a[j];
            a[j]=min;
            min=temp;
        }
        printf("%d ",a[j]);
    }
}

2 Answers2

0

min is used as an index(min=j) instead of value(min=a[j])

Like this :

min=j;
for(k=j;k<6;k++)
{
    if(a[k]<a[min]){//if(a[k]>a[min]){
        min=k;
    }
}

temp=a[j];
a[j]=a[min];
a[min]=temp;
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0

Some advice for you, although it's probably a duplicate. When you call k++ when indexing your array (a[k++]), you always increment k although you did not finish the loop. So the for(k.....) loop does not pass all your other array elements.

greyhairredbear
  • 624
  • 3
  • 10
  • 27