package utils.sort;
/**
*@author linyco
*利用选择排序法对数组排序,数组中元素必须实现了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;
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;
}
}//将最小的元素交换到前面
tmp = obj[i];
obj[i] = obj[index];
obj[index] = tmp;
} } }
闽公网安备 35060202000074号