Hobbit
Hobbit

Reputation: 11

Basic array doubts

public class Quicks
{
    public static void main(String args[])
    {   int temp;
        int[] list={5,1,7,6,4,0,8,9};
        int i;
        for(i=0;i<=6;i++)
        {
            if(list[i]>list[i+1]);
            {   
                temp=list[i+1];
                list[i+1]=list[i];
                list[i]=temp;
                
            }
        
        }
        for(i=0;i<=6;i++)
        {
            System.out.println(list[i]);
        }
            
        }
    }
    

this is the output i am getting 1 7 6 4 0 8 9

MY first doubt is where is 5

why is 7 and 6 not being swapped

Upvotes: 1

Views: 158

Answers (2)

Jaroslaw Pawlak
Jaroslaw Pawlak

Reputation: 5578

If you used IDE, it should show you a warning saying that your if statemenet has an empty body - this is because you have put a semicolon at the end of line which shouldn't be there.

I would recommend to put braces { at the end of line, rather than the next line to avoid such mistakes.

As for why 5 is not printed - as others mentioned you do not iterate over the entire array.

Upvotes: 0

Shondeslitch
Shondeslitch

Reputation: 1079

Your first question.

Your loop:

for(i=0;i<=6;i++)
{
     System.out.println(list[i]);
}

Would be:

for(i=0;i<=7;i++)
{
    System.out.println(list[i]);
}

because of the size of your array is 8 and no 7, and 6-0+1 = 7, so you don't print the last element.

And if you analize your code, you will accounts that the loop move the first element of your array to the last position. If you want to sort your array this is not the code.

Upvotes: 5

Related Questions