數組——插入排序法(對隨機數進行排序)

class InsertSort{
//插入排序法
public void sort(int array[]){
for(int i=1; i<array.length; i++){
int insertVal = array[i];
int index = i-1;
while(index>=0 && insertVal<array[index]){
array[index+1] = array[index];
index--;
}
array[index+1] = insertVal;
}
}
}

class Test{
public static void main(String args[]){
int array[] = new int[6];
System.out.println("生成6個0~99的隨機數:");
for(int i=0; i<array.length; i++){
array[i] = (int)(Math.random()*100);
System.out.print(array[i]+" ");
}
InsertSort is = new InsertSort();
is.sort(array);
System.out.println("\n用插入排序法排序後爲:");
for(int i=0; i<array.length; i++){
System.out.print(array[i]+" ");
}

}
}
/********************************
生成6個0~99的隨機數:
46 10 39 84 71 64
用插入排序法排序後爲:
10 39 46 64 71 84
********************************/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章