Dan S.
Dan S.

Reputation: 87

Sorting double arrays into ascending order

I'm currently trying to sort a Double Array into ascending order manually. The problem I'm having is that the output only lists the 1st smallest value at the top (which is correct), but lists the rest of the values given as 0.0. (The values range from -5 to +20). Below is my coding attempt at sorting. Any help will be greatly appreciated. Thank you.

             int index; 
             double temp;

             for(index = 0; index < x.length; index++)
               { 
                 for(int j = 0; j < x.length - 1; j++)
                    {
                       if(x[j + 1] < x[j])
                          {
                             temp = x[j + 1];
                             x[j + 1] = x[j];
                             x[j] = temp;  
                           }
                      }
                }

Upvotes: 0

Views: 7362

Answers (3)

GriffeyDog
GriffeyDog

Reputation: 8376

You're close, but you need to compare x[index] with x[j]:

for (int index = 0; index < x.length - 1; index++) {
  for (int j = index + 1; j < x.length; j++) {
    if (x[j] < x[index]) {
      temp = x[j];
      x[j] = x[index];
      x[index] = temp;
    }
  }
}

Upvotes: 1

Chase
Chase

Reputation: 1431

You can use Arrays.sort(x) from the java.util package to sort your array.

Upvotes: 1

Jannis Alexakis
Jannis Alexakis

Reputation: 1319

That´s almost bubblesort you got there. try this :

 public static void sort(int[] x) {
  boolean sorted=true;
  int temp;

  while (sorted){
     sorted = false;
     for (int i=0; i < x.length-1; i++) 
        if (x[i] > x[i+1]) {                      
           temp       = x[i];
           x[i]       = x[i+1];
           x[i+1]     = temp;
           sorted = true;
        }          
  } 

}

But Collin is right. You are better off with Arrays.sort.

Upvotes: 1

Related Questions