選擇排序算法實現過程:
算法描述:從頭至尾掃描待排序序列,找出該序列中最小(大)的元素和第一個元素交換位置。接着從剩下的元素序列中重複前面的操作,最終得到一個有序序列。
實現過程:使用兩個for循環,第一個for循環確定存放待排序序列中經選擇和交換之後的最小(大)的元素。第二個for循環實現將之前確定的最小(大)元素與序列中剩餘的元素進行比較交換出最小(大)元素的下標。
圖解:
代碼:
public class SelectionSort {
public static void main(String[] args){
// Boolean b = true;
int k = 1;
Scanner in = new Scanner(System.in);
String s = in.nextLine();
// 鍵盤輸入數據時,使用逗號將各個元素隔開
String[] array = s.split(",");
// 定義一個int類型的數組準備進行String與int之間的轉換
int[] arr = new int[array.length];
System.out.println("輸入數據:");
// 異常機制
try{
for(int i=0; i<arr.length; i++){
arr[i] = Integer.parseInt(array[i]);
System.out.print(arr[i]+" ");
}
}catch(Exception e){
// b=false;
k=0;
System.out.println("輸入數據有誤!!!");
}
// 方法調用(靜態方法)
System.out.println();
if(k==1){
selectionSort(arr);
}else{
System.out.println("無法輸出!!!");
}
}
// 選擇排序算法
public static void selectionSort(int[] array){
System.out.println("選擇排序之後:");
for(int i=0; i<array.length; i++){
int index = i;
int j;
for(j=i+1; j<array.length; j++){
if(array[j]<array[index]){
index = j;
}
}
int temp = array[index];
array[index] = array[i];
array[i] = temp;
System.out.print(array[i]+" ");
}
}
}
參考文獻地址:
-
https://blog.csdn.net/changhangshi/article/details/82740541
-
https://blog.csdn.net/qq_39360985/article/details/78808171
-
http://c.biancheng.net/view/524.html