2017-06-06 59 views
0

此程序用於列出10名學生及其標記。然後我想用Bubble排序。這裏發生問題。標記正在排序。但名字仍然在同一個地方。排序後,名稱保持在同一位置,標記按照升序排列。Bubble Sort Strings

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; 
       } 
      } 
     } 
    } 
} 
+4

寫一個類***學生***與屬性***名稱,標記***,拿起一個條件進行排序,使用getters .... –

+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 
+0

感謝您的幫助 – Tippu