我对选择排序有一些疑问.我有点困惑.
int [] arr = {5,4,3,2,1}; // This is my array
int min = 0;
for(int i = 0;i<arr.length;i++)
{
//Assume first element is min
min = i;//Selection sort algorithm says that find the minimum in the
// array, but first element is not minimum.What's point here?
for(int j = i + 1;j<arr.length;j++)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
System.out.println(arr[i]);//I print the in ascending order
}
}
输出是:
4
3
2
1
4
3
2
4
3
4
怎么了 ?
解决方法:
选择排序是关于在循环的每个步骤中找到最小值.你没有找到最小值(可能是if语句),只需简单地交换内循环中的值即可.所以你实际上没有做一个排序.
根据您的实施进行更正:
final int[] arr = { 5, 4, 3, 2, 1 }; // This is my array
int min;
for (int i = 0; i < arr.length; i++) {
// Assume first element is min
min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
if (min != i) {
final int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
System.out.println(arr[i]);// I print the in ascending order
}
这应该给你输出:
1
2
3
4
5