0

I'm trying to sort an array that include 5 numbers(size=4) from largest to smallest, but I spend a long time and I don't know why my code don't take the first element to be sorted..

This is My code:

public class sortingS
{
public static void main(String []args)
{
    int a[]={5,-2,10,14,-1};
    for(int i=0; i<a.length; i++)
    {
        for(int j=0; j<i; j++)
        {
            if(a[i]>a[j+1])
            {
                int temp=a[j+1];
                a[j+1]=a[i];
                a[i]=temp;
            }
        }
    }
    for(int i=0; i<a.length; i++){
        System.out.println(a[i]);
    }
}
}

and this is the output:

5 14 10 -1 -2

1
  • 1
    What did you find when you stepped through this code in your debugger? Commented Jan 22, 2016 at 17:56

2 Answers 2

1

For some reason, you are comparing the element past the current index of j; you're always using j+1. Stop adding 1 to j wherever you use it. You're skipping the first element that way.

if(a[i] > a[j])
{
    int temp = a[j];
    a[j] = a[i];
    a[i] = temp;
}
Sign up to request clarification or add additional context in comments.

Comments

0

It's a bubble sort. You can find some explanation here and here.

public static void main(String args[]){

int[] vet = {8, 9, 3, 5, 1};
int aux = 0;
int i = 0;

System.out.println("Original Array: ");

for(i = 0; i<5; i++){
 System.out.println(" "+vet[i]);
}

System.out.println(" ");

for(i = 0; i<5; i++){
      for(int j = 0; j<4; j++){
          if(vet[j] > vet[j + 1]){
                aux = vet[j];
                vet[j] = vet[j+1];
                vet[j+1] = aux;
          }
      }
}

System.out.println("Ordered Array:");
    for(i = 0; i<5; i++){
          System.out.println(" "+vet[i]);
    }
}

3 Comments

Gonna provide any sort of explanation?
Why don't you open your own question?
Because I don't need a question answered. It was more of a hint that pasting code and saying nothing about it is bad practice. Pasting code and links about it is barely better. You have made no attempt to explain specifically how this solves the OP's specific problem.

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.