Sunday, May 16, 2004

 

Sorts總整理1--Insertion Sort

雖然期中考過很久了
不過還是要把Sorts 整理整理
希望有需要的人也可以參考看看

《Insertion Sort》

Algorithm :
Insertion-Sort(A)
for j←2 for length[A]
   do keyA[j]
      △Insert A[j] into the sorted sequence A[1..j-1]

      ij-1
      while i>0 and A[i]>key
         do A[i+1]←A[i]
            ii-1
         A[i+1]←key

java code:整數排序
void insertionSort(int[] Array){
   for(int j = 1; j < Array.length; j++){
      int key = Array[j];
      int i = j - 1;
      while( (i >= 0) && (Array[i] > key) ){
         Array[i+1] = Array[i];
         i--;
      }
      Array[i+1] = key;
   }
}
java code:字串排序
void insertionSort(String[] Array) {
   for (int j = 1; j < Array.length; j++) {
      String key = Array[j].name;
      int i = j - 1;

      while ((i >= 0) && (Array[i].name.compareTo(key)> 0)) {
         Array[i + 1].name = Array[i].name;
         i--;
      }

      Array[i + 1].name = key;
   }
}
由 shumi 發表於 May 16, 2004 11:30 PM

Comments: Post a Comment



<< Home