0

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.

4

2 回答 2

0

正如其他人所提到的,最好阅读冒泡排序算法。为了回答您的问题,每次两个元素乱序时(当较大的数字在较小的数字之前)时,都会使用交换函数。一个伪代码示例是:

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()

那就是冒泡排序!我希望这有帮助。

于 2013-11-16T04:36:53.803 回答
-1

这是您应该使用世界上最简单的排序算法的地方:冒泡排序。 单击此处查看逐步描述如何操作的维基百科文章。

如果您仍然遇到问题,请对此回复发表评论。

于 2013-11-14T06:52:19.270 回答