package 算法;public class SelectionSort { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub int[] num = { 9, 13, 3, 5, 7, 45, 72, 23, 2 };
int smallIndex, pass, i;
int temp;
for (pass = 0; pass < num.length - 1; pass++) {
smallIndex = pass;
for (i = pass + 1; i < num.length; i++) {
if (num[i] < num[smallIndex])
smallIndex = i; temp = num[smallIndex];
num[smallIndex] = num[pass];
num[pass] = temp; }
} for (int j = 0; j < num.length; j++) {
System.out.print(num[j] + " ");
} }}大家帮我看一下,为什么结果会错呢2 5 3 7 9 13 23 45 72
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub int[] num = { 9, 13, 3, 5, 7, 45, 72, 23, 2 };
int smallIndex, pass, i;
int temp;
for (pass = 0; pass < num.length - 1; pass++) {
smallIndex = pass;
for (i = pass + 1; i < num.length; i++) {
if (num[i] < num[smallIndex])
smallIndex = i; temp = num[smallIndex];
num[smallIndex] = num[pass];
num[pass] = temp; }
} for (int j = 0; j < num.length; j++) {
System.out.print(num[j] + " ");
} }}大家帮我看一下,为什么结果会错呢2 5 3 7 9 13 23 45 72
public class SelectionSort { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub int[] num = { 9, 13, 3, 5, 7, 45, 72, 23, 2 };
int smallIndex, pass, i;
int temp;
for (pass = 0; pass < num.length - 1; pass++) {
smallIndex = pass;
for (i = pass + 1; i < num.length; i++) {
if (num[i] < num[smallIndex])
smallIndex = i;
}
temp = num[smallIndex]; //这三行代码移出第二重循环
num[smallIndex] = num[pass];
num[pass] = temp; } for (int j = 0; j < num.length; j++) {
System.out.print(num[j] + " ");
}
}
}
选择排序是每一轮找到最小的数放在前面
不过这个代码效率太低了public class SelectionSort { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub int[] num = { 9, 13, 3, 5, 7, 45, 72, 23, 2 };
int smallIndex, pass, i;
int temp;
for (pass = 0; pass < num.length - 1; pass++) {
//smallIndex = pass;
for (i = pass + 1; i < num.length; i++) {
if (num[i] < num[pass]) {
//smallIndex = i;
temp = num[pass];
num[pass] = num[i];
num[i] = temp;
}
}
} for (int j = 0; j < num.length; j++) {
System.out.print(num[j] + " ");
} }}