Method to sort an array in Java

Mar :

I've been working on a method that sorts an array from lowest to highest number. I came up with the code below but, as you probably guessed, it doesn't do what I expected.

The logic I wished to apply goes as follows:

Given I have an array, for example array {4,3,1,2,5} The code would compare, for example, array[0] (which would be four in this case) with each element in the array,

array[0]>array[0] (4>4=false), 
array[0]>array[1] (4>3)= +1counter, 
array[0]>array[2] (4>1)= +1counter, 
array[0]>array[3] (4>2)= +1counter,
array[0]>array[4] (4>5=false)

counter = 3

So since the counter value its now 3, in the new array (array2, or arrayOrdered) number 4 would be in the third index.

How should I fix it? Any help its more than appreciated!

public static int[] OrderArray(int[] array)
{

    int[] array2=new int[array.length];

    for (int i=0; i<array.length; i++)
    {
        int place=0;
        for (int j=0; j<array.length;j++)
        {
            if (array[i]> array[j])
            {
                place = place+1;
            }
            array2[place] = array[i];
        }

    }
    return array2;
}
Trevor Freeman :

What you are looking to do is called sorting, and there are many known sorting algorithms with different characteristics you can use to accomplish what you want.

You can read about many of the different sorting algorithms here: https://en.wikipedia.org/wiki/Sorting_algorithm

Java itself has built in sorting functionality, and you can sort an array using the Arrays.sort method, which uses a very fast and well known Quicksort algorithm for arrays of ints.

As other commentators have discussed, your sorting algorithm appears flawed, and overall appears to be closest to an Insertion Sort algorithm, which you may want to look at for some ideas: https://en.wikipedia.org/wiki/Insertion_sort

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

Pseudocode from the above link:

i ← 1
while i < length(A)
    j ← i
    while j > 0 and A[j-1] > A[j]
        swap A[j] and A[j-1]
        j ← j - 1
    end while
    i ← i + 1
end while

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=311482&siteId=1