带输出的气泡排序 [英] Bubble sort with output

查看:94
本文介绍了带输出的气泡排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我已经对其进行了一些编辑,并且几乎完全得到了我想要的.我现在遇到的唯一问题是,我得到了我不想要的输出行.我觉得这里的解决方法很简单,但是现在我的大脑已经炸了.

So I have edited it some and am getting almost exactly what I want. The only problem I am having now is that I am getting a line of output that I don't want. I feel like the fix here is simple but my brain is fried right now.

static void bubbleSort(int[] myArray) {
    int n = myArray.length;
    int temp = 0;
    int counter = 0;
    for (int i = 0; i < n; i++) {
        int k;
        for (k = 0; k < n; k++) {
            System.out.print(myArray[k] + "|");
        }
        System.out.println(" Num swaps: " + counter);
        for (int j = 1; j < (n - i); j++) {
            if (myArray[j - 1] > myArray[j]) {
                //swap elements
                temp = myArray[j - 1];
                myArray[j - 1] = myArray[j];
                myArray[j] = temp;
                counter++;
            }
        }
    }
}

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int[] myArray = new int[10];
    for (int i = 0; i < 10; i++) {
        System.out.print("Enter slot " + i + ": ");
        myArray[i] = sc.nextInt();
    }
    bubbleSort(myArray);
}

以下是我所得到的例子:

Here is an example of what I get:

Enter slot 0: 10
Enter slot 1: 9
Enter slot 2: 8
Enter slot 3: 7
Enter slot 4: 6
Enter slot 5: 5
Enter slot 6: 4
Enter slot 7: 3
Enter slot 8: 2
Enter slot 9: 1
10|9|8|7|6|5|4|3|2|1| Num swaps: 0
9|8|7|6|5|4|3|2|1|10| Num swaps: 9
8|7|6|5|4|3|2|1|9|10| Num swaps: 17
7|6|5|4|3|2|1|8|9|10| Num swaps: 24
6|5|4|3|2|1|7|8|9|10| Num swaps: 30
5|4|3|2|1|6|7|8|9|10| Num swaps: 35
4|3|2|1|5|6|7|8|9|10| Num swaps: 39
3|2|1|4|5|6|7|8|9|10| Num swaps: 42
2|1|3|4|5|6|7|8|9|10| Num swaps: 44
1|2|3|4|5|6|7|8|9|10| Num swaps: 45

输出的第一行,它重复用户输入的内容并说0交换.我不要那个.

That first line of output where it just repeats what the user input and says 0 swaps. I don't want that.

推荐答案

只需更改for循环的位置.希望这是您真正想要的输出:).

Just changed the position of the for loops. Hope this is the output you actually want :).

static void bubbleSort(int[] myArray) {
    int n = myArray.length;
    int temp = 0;
    int counter = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {
            if (myArray[j - 1] > myArray[j]) {
                // swap elements
                temp = myArray[j - 1];
                myArray[j - 1] = myArray[j];
                myArray[j] = temp;
                counter++;
            }
        }
        int k;
        for (k = 0; k < n; k++) {
            System.out.print(myArray[k] + "|");
        }
        System.out.println(" Num swaps: " + counter);
    }
}

这篇关于带输出的气泡排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆