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
  • Thank you, that question did help me, but I want to know why my code is not correct. Commented Mar 25, 2016 at 21:25
  • 1
    This is still off-topic as given. Learn How to Ask. And use a debugger. Commented Mar 25, 2016 at 21:29

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.