Algorithm’ thought:Therer is a array with x number.First round find a minimum number,move it out of array,and next round make the ramaining number compare,The advantage of selection sort relative to bubble sort is :Every exchange of positions makes sense.“i” means index of first number that taking part in comparison.The point is assume that the date with index “i” is smallest number.
Code:
public static void main(String[] args) {
for (int i = 0; i < arr.length-1; i++){
int min = i;
for (int j = i+1; j < arr.length; j++) {
if (arr[j]<arr[min]){
min = j;
}
if (min != i){
int tmp;
tmp = arr[min];
arr[min] = arr[i];
arr[i] = tmp;
}
}
}
}
外层循环进行length-1次比较,内层先假定下标为i(也就是每次比较的数据中的第一个),第一个if语句确保min代表的最小元素的下标,第二个if语句确保当下标改变了之后,下标表示的元素也相应替换。