public class TestSortArgs {
public static void print(int [] temp) {//打印數組算法
for(int i=0;i<temp.length;i++) {
System.out.print(" " + temp[i]);
}
}
/******************************************************************/
public static void selectSort1(int [] temp) {//選擇排序算法,效率不高
for(int i=0;i<temp.length;i++){
for(int j=i+1;j<temp.length;j++) {
if(temp[i]>temp[j]) {
int in ;
in = temp[i] ;
temp[i] = temp[j] ;
temp[j] = in ;
}
}
}
}
/******************************************************************/
public static void selectSort2(int []a) {//選擇排序算法,效率較前者更好
int k,temp ;
for(int i=0;i<a.length;i++) {
k = i ;
for(int j=k+1;j<a.length;j++) {
if(a[j] < a[k])
k = j ;
}
if(k != i) {
temp = a[i] ;
a[i] = a[k] ;
a[k] = temp ;
}
}
}
/******************************************************************/
public static void main(String [] args) {
int a[] = new int[args.length] ;
for(int i=0;i<args.length;i++){
a[i] = Integer.parseInt(args[i]) ;
}
TestSortArgs t = new TestSortArgs();
System.out.print("you have input the array:");
t.print(a);
System.out.println();
System.out.print("After selectSort the array is:");
//t.selectSort1(a);//調用選擇排序算法1
t.selectSort2(a);//調用選擇排序算法2
t.print(a);
}
}
2種選擇排序算法的效率比較(帶測試main方法)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.