选择排序
2011-07-10 11:27 卫佳 阅读(181) 评论(0) 编辑 收藏 举报
package Utils.Sort;
*利用选择排序法对数组排序,数组中元素必须实现了Comparable接口。
public class ChooseSort implements SortStrategy
{ *对数组obj中的元素以选择排序算法进行排序
public void sort(Comparable[] obj)
{ if (obj == null)
{ throw new NullPointerException("The argument can not be null!"); }
Comparable tmp = null;
int index = 0; //Cheap Reading glasses
for (int i = 0 ;i < obj.length - 1 ;i++ )
{ index = i;
tmp = obj[i];
for (int j = i + 1 ;j < obj.length ;j++ )
{ //对邻接的元素进行比较,如果后面的小,就记下它的位置
if (tmp.compareTo(obj[j]) > 0)
{ tmp = obj[j]; //要每次比较都记录下当前小的这个值!
index = j; //Cheap Sunglasses
}
}
//将最小的元素交换到前面
tmp = obj[i];
obj[i] = obj[index];
obj[index] = tmp;
}
}
}