3

Sorting numbers with arrays

 2 years ago
source link: https://www.codesd.com/item/sorting-numbers-with-arrays.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Sorting numbers with arrays

advertisements

Im really new to programming in Java so any answers don't be shy in really dumbing it down as much as possible.

I'm trying to create a program that will take an array value and sort it from smallest to largest number. This is what I've got so far:

public class ArraySwap
{
    public static void main(String[] args)
    {
        int[a] = new int[4];
        a[0] = 5;
        a[1] = 7;
        a[2] = 2;
        a[3] = 1;

        for (int i = a.length-1;

Thats what I've got so far, but I've no idea what to use in the for loop, it has to be an actual code formula with a for loop so no using array.sort or anything like that.

The output should re-arrange the numbers so they display 1 2 5 7 instead of 5 7 2 1 which is what they would be if I just had it print them out down the list.

My teacher gave me an example of what to use as this:

    void swap (int x, int y)
{
int temp;
temp = x
x = y
y = temp;
}

But I have no idea how to use this in the program.


As mentioned by others, it would be good to read up on bubble sorting algorithms. To answer your question, the swap function would be used every time two elements are out of order (when a larger number is before a smaller number). A pseudo-code example would be:

loop until no element changes through one cycle
    for every element in the array minus one
        if one element is greater than the element after it
            swap()

And that is bubble sort! I hope this helps.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK