package Utils.Sort;
/** *@author Linyco *利用選擇排序法對(duì)數(shù)組排序,數(shù)組中元素必須實(shí)現(xiàn)了Comparable接口。 */ public class ChooseSort implements SortStrategy { /** *對(duì)數(shù)組obj中的元素以選擇排序算法進(jìn)行排序 */ public void sort(Comparable[] obj) { if (obj == null) { throw new NullPointerException("The argument can not be null!"); }
Comparable tmp = null; int index = 0;
for (int i = 0 ;i < obj.length - 1 ;i++ ) { index = i; tmp = obj[i];
for (int j = i + 1 ;j < obj.length ;j++ ) { //對(duì)鄰接的元素進(jìn)行比較,如果后面的小,就記下它的位置 if (tmp.compareTo(obj[j]) > 0) { tmp = obj[j]; //要每次比較都記錄下當(dāng)前小的這個(gè)值! index = j; } }
//將最小的元素交換到前面 tmp = obj[i]; obj[i] = obj[index]; obj[index] = tmp; } } } |
|