带有冒泡排序的数组

时间:2015-04-12 11:28:27

标签: java arrays

我的任务是使用冒泡排序算法对数组(我的成绩(int)所在的位置)进行排序,我已经完成了。

但我也希望它打印出来自另一个数组的名称,该数组包含相同顺序中每个等级的以下名称。

我该怎么做?

package assignment9.pkg1;

import java.util.Scanner;

/**
 *
 * @author Anders
 */
public class Assignment91 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    String studName = "Anders";
    int counter = 3;
    System.out.println(" welcome to student database, show informations about student" + studName);

    Scanner courseScan = new Scanner(System.in);
    Scanner gradeScan = new Scanner(System.in);
    Scanner counterScan = new Scanner(System.in);

    System.out.println(" Enter the number of courses");

    String[] courseArray = new String[counter];
    int[] gradeArray = new int[counter];

    for (int k = 0; k < counter; k++) {

        if (20 < counter) {

            System.out.println(" no more space");
        } else {

            System.out.println(" enter name");
            courseArray[k] = courseScan.nextLine();
            System.out.println(" Enter grade");
            gradeArray[k] = gradeScan.nextInt();
        }
    }

    int n = gradeArray.length;
    int temp = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {

            if (gradeArray[j - 1] > gradeArray[j]) {
                //swap the elements!
                temp = gradeArray[j - 1];
                gradeArray[j - 1] = gradeArray[j];
                gradeArray[j] = temp;

            }

        }

    }

    for (int l = 0; l < counter; l++) {

        System.out.println(gradeArray[l] + courseArray[l]);
    }
}
}

1 个答案:

答案 0 :(得分:0)

在循环中,修改的等级顺序也会修改课程数组的顺序

for (int i = 0; i < n; i++) {
    for (int j = 1; j < (n - i); j++) {

        if (gradeArray[j - 1] > gradeArray[j]) {
            //swap the elements!
            temp = gradeArray[j - 1];
            gradeArray[j - 1] = gradeArray[j];
            gradeArray[j] = temp;

            //swap the course name !
            String stringTemp;
            stringTemp = courseArray[j - 1];
            courseArray[j - 1] = courseArray[j];
            courseArray[j] = stringTemp;

        }

    }

}