初学者:用java程序写一个选择排序算法!

来源:百度知道 编辑:UC知道 时间:2024/05/10 06:23:07
注意:要用选择排序法!不是冒泡法!

选择排序法:
public class TSort{
public static void main(String args[]){
int a[]={12,45,2,5,26,56};
for(int i=0;i<a.length-1;i++){
int t;
for(int j=i+1;j<a.length;j++){
if(a[i]>a[j]){
t=a[i];a[i]=a[j];a[j]=t;
}
}
}
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
}

package Utils.Sort;

/**
*@author Linyco
*利用选择排序法对数组排序,数组中元素必须实现了Comparable接口。
*/

public class ChooseSort
implements SortStrategy

{
/**
*对数组obj中的元素以选择排序算法进行排序
*/
public void sort(Comparable[] obj) {
if (obj == null) {
throw new NullPointerException("The argument can not be null!");
}
Comparable tmp = null;
int index = 0;
for (int i = 0; i < obj.length - 1; i++) {
index = i;
tmp = obj[i];
for (int j = i + 1; j < obj.lengt