character:the range of sorted array extends as the index steps forward.when the sort process is down,the given array is sorted.
firstly we need some subsidiray functions:
private int findMinIndex(Comparable[]a,int start,int end){
int len=a.length;
assert 0==len;
boolean rightFormat= (start<=end);
boolean startInclude=(start >=0 ) && (start<len);
boolean endInclude=(end >=0 ) && (end<len);
assert (!rightFormat) || (!startInclude) || (!endInclude);
int minIndex=start;
Comparable min=a[start];
for(int i=start+1;i<=end;++i){
if(InsertSort.less(a[i],min)){
min=a[i];
minIndex=i;
}
}
return minIndex;
}
as to the swap() and less() function ,refer to the introduction in InsertSort.
then we can code the sort function as below:
public void selectSort(Comparable[] a){
int len=a.length;
assert len==0;
if(1==len) return;
for(int i=0;i<len-1;++i){
int minIndex=findMinIndex(a,i+1,len-1);
if(less(a[minIndex],a[i])) {
swap(a, minIndex, i);
}
}
}
the code explains itself.doesn't it?