package hq;
import java.util.Scanner;
public class selectionSort {
//将a【】按升序排列
public static void sort(Comparable[] a){
for(int i = 0;i < a.length;i++){
//将a【i】和a【i+1..n】中最小的元素交换
int min = i;//最小的元素索引
for( int j = i+1;j < a.length;j++){
if(less(a[j],a[min])) min = j;
exch(a,i,min);
}
}
}
private static boolean less(Comparable v,Comparable w){//比较两者大小,前者大于后者返回ture
return v.compareTo(w) < 0;
}
private static void exch(Comparable[] a,int i,int j){// 交换两个数组
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
private static void show(Comparable[] a){//在单行中打印数组
for(int i = 0;i<a.length;i++)
System.out.print(a[i] + “,”);
System.out.println();
}
public static boolean isSorted(Comparable[] a){//测试数组元素能否有序
for(int i = 1;i < a.length;i++)
if(less(a[i],a[i-1])) return false;
return true;
}
public static void main(String[] args) {
selectionSort sls = new selectionSort();
Comparable[] a = {1,3,2,5,9,0,4,8};
// Scanner s = new Scanner(System.in);
// System.out.println(“请输入要排序的一组数并用逗号隔开:”);
// String inputString = s.next().toString();
// s.close();
// String stringArray[] = inputString.split(“,”);
// Comparable a[] = new Comparable[stringArray.length];
// for(int i = 0;i < stringArray.length;i++){
// a[i] =Integer.parseInt(stringArray[i]);
// }
sls.sort(a);
assert sls.isSorted(a);
System.out.println(“排序的结果为:”);
sls.show(a);
}
}
import java.util.Scanner;
public class selectionSort {
//将a【】按升序排列
public static void sort(Comparable[] a){
for(int i = 0;i < a.length;i++){
//将a【i】和a【i+1..n】中最小的元素交换
int min = i;//最小的元素索引
for( int j = i+1;j < a.length;j++){
if(less(a[j],a[min])) min = j;
exch(a,i,min);
}
}
}
private static boolean less(Comparable v,Comparable w){//比较两者大小,前者大于后者返回ture
return v.compareTo(w) < 0;
}
private static void exch(Comparable[] a,int i,int j){// 交换两个数组
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
private static void show(Comparable[] a){//在单行中打印数组
for(int i = 0;i<a.length;i++)
System.out.print(a[i] + “,”);
System.out.println();
}
public static boolean isSorted(Comparable[] a){//测试数组元素能否有序
for(int i = 1;i < a.length;i++)
if(less(a[i],a[i-1])) return false;
return true;
}
public static void main(String[] args) {
selectionSort sls = new selectionSort();
Comparable[] a = {1,3,2,5,9,0,4,8};
// Scanner s = new Scanner(System.in);
// System.out.println(“请输入要排序的一组数并用逗号隔开:”);
// String inputString = s.next().toString();
// s.close();
// String stringArray[] = inputString.split(“,”);
// Comparable a[] = new Comparable[stringArray.length];
// for(int i = 0;i < stringArray.length;i++){
// a[i] =Integer.parseInt(stringArray[i]);
// }
sls.sort(a);
assert sls.isSorted(a);
System.out.println(“排序的结果为:”);
sls.show(a);
}
}
解决方案
20
int min = i;//最小的元素索引
你的最小索引,在每次循环时会被赋值
你的最小索引,在每次循环时会被赋值
20
改两行代码:
//min = j; 把它注释了
exch(a, j, min); //把 i换成j
//min = j; 把它注释了
exch(a, j, min); //把 i换成j