冒泡排序字符串

时间:2017-06-06 07:03:14

标签: java sorting bubble-sort

此计划适用于列出10名学生及其分数。然后我想用Bubble排序对它进行排序。这里出现问题。标记正在排序。但这个名字仍然在同一个地方。排序后,名称保持在同一位置,标记按升序移动。

public class StudentResult {
    public static void main(String [] args) {
        String names[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
        int marks[] = { 100, 20, 30, 40, 50, 60, 32, 80, 90, 10 };
        System.out.println("Students              Marks");
        System.out.println("____________________________");
        for (int i = 0; i < names.length; i++)
            System.out.println(names[i] + "          -          " + marks[i]);
        bubbleSort(marks, names);
        System.out.println("\n\n\nSorted List\n\n");
        System.out.println("Students              Marks");
        System.out.println("____________________________");
        for(int i = 0; i < marks.length; i++)
            System.out.println(names[i] + "          -          " + marks[i]);
    }

    static void bubbleSort(int[] marks, String[] names) {
        int n = marks.length;
        int m = names.length;
        int temp = 0;
        for(int i=0; i < n; i++){
            for(int j=1; j < (n-i); j++){
                if(marks[j-1] > marks[j]){
                    //swap elements
                    temp = marks[j-1];
                    marks[j-1] = marks[j];
                    marks[j] = temp;
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

只需在冒泡排序方法中进行一些小改动,如下所示:

static void bubbleSort(int[] marks, String[] names) {
    int n = marks.length;
    int m = names.length;
    int temp = 0;
    String temp1 = null;
    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {
            if (marks[j - 1] > marks[j]) {
                // swap elements
                temp = marks[j - 1];
                marks[j - 1] = marks[j];
                marks[j] = temp;
                temp1 = names[j - 1];
                names[j - 1] = names[j];
                names[j] = temp1;
            }
        }
    }
}

这将给出程序的以下输出:

Students       Marks
______________________
a        -      100
b        -       20
c        -       30
d        -       40
e        -       50
f        -       60
g        -       32
h        -       80
i        -       90
j        -       10



Sorted List

Students       Marks
______________________
j        -       10
b        -       20
c        -       30
g        -       32
d        -       40
e        -       50
f        -       60
h        -       80
i        -       90
a        -      100