Monday, May 17, 2004

 

Sorts總整理5--Bubble Sort

Bubble Sort的演算法和程式碼

《Bubble Sort》

Algorithm :
Bubblesort(A)
for i←1 to length[A]
   do for jlength[A] downto i+1
      do if A[j]<A[j-1]
         then exchange A[j]←→A[j-1]

java code:整數排序
void bubbleSort(int[] Array) {
   int temp;

   for (int i = 0; i < Array.length; i++) {
      for (int j = 0; j < (Array.length - i - 1); j++) {
         if (Array[j].score > Array[j + 1].score) {
            temp = Array[j].score;
            Array[j].score = Array[j + 1].score;
            Array[j + 1].score = temp;
         }
      }
   }
}
java code:字串排序
void bubbleSort(String[] Array) {
   String temp;

   for (int i = 0; i < Array.length; i++) {
      for (int j = 0; j < (Array.length - i - 1); j++) {
         if (Array[j].name.compareTo(Array[j + 1].name) > 0) {
            temp = Array[j].name;
            Array[j].name = Array[j + 1].name;
            Array[j + 1].name = temp;
         }
      }
   }
}
由 shumi 發表於 May 17, 2004 08:41 AM

Comments: Post a Comment



<< Home