organizing numbers in an array in Java

2.6k Views Asked by At

Im trying to organize random numbers in an array from least to greatest. I came up with a loop which I thought should work but has a lot of logic errors.

 for(int z=0; z<=999;z++){
    for(w=1; w<=999;w++){
      if(z<w){
        if(numberArray[z]<numberArray[w])
         temp=numberArray[w];
        }
    }
    numberArray[z]=temp;
  }

Can anyone tell me how to fix this or an algorithm of their own for doing this?

3

There are 3 best solutions below

1
On

Arrays.sort() is a quick and easy way.

Also consider PriorityQueues if you need something a little more robust!

This link is another question on SO with a great answer.

0
On

One liner:

Arrays.sort(numberArray);

Or greatest to least order:

Arrays.sort(numberArray, Collections.reverseOrder());

Or even better, use a Binary Search Tree that keeps its contents in sorted order, this is great for collections that are pretty dynamic, as the add operation is cheaper memory wise and time wise than a full in-place sort:

TreeSet<int> set = new TreeSet<int>();
set.add(10);
set.add(4);
set.add(11);

set.toString();
// prints 4, 10, 11
1
On

There are several ways you can sort an array in Java. Here I post but 3 of them : the core library, and 2 algorithms you can make on your own.

1 ) Core one: This is literally only one line of code. I would suggest using this - simple, and very efficient, compared to the below two solutions.

Arrays.sort(myArray);

2 ) Selection Sort : Find the lowest value in an array, move it to the first position, find the next lowest, move to 2nd position, etc.

public void selectionSort(Comparable[] a)
{
    for(int index = 0; index < a.length; index++)
    {
        // find the smallest one in the array from index : end
        int smallest = indexOfMin(a, index);
        // swap the value at index and the value at the smallest one found
        Comparable temp = a[smallest];
        a[smallest] = a[index];
        display.update();
        a[index] = temp;
    }
}

3 ) Insertion Sort : Inserts each element in the array into a growing sequence of sorted values and finishes at the end of the array.

public void insertionSort(Comparable[] a)
{
    for(int i = 1; i < a.length; i++)
    {
        insert(a, i);
    }
}

public void insert(Comparable[] a, int nextIndex)
{
    int index = 0;
    Comparable finalObject = a[nextIndex];
    // Let us first find the first occurence of a comparable greater than our comparable
    while(finalObject.compareTo(a[index]) > 0)
        index++;
    for(int i = (nextIndex-1); i >= index; i--)
        a[i+1] = a[i];
    a[index] = finalObject;
}