Java 資料結構 - 選擇排序
選擇排序是一種簡單的排序演算法。這種排序演算法是一種原地比較排序演算法,其中列表被分成兩個部分,排序部分在左側,未排序部分在右側。最初,排序部分為空,未排序部分是整個列表。
從未排序陣列中選擇最小的元素,並將其與最左邊的元素交換,該元素成為排序陣列的一部分。此過程繼續將未排序陣列邊界向右移動一個元素。
此演算法不適用於大型資料集,因為其平均和最壞情況複雜度為 Ο(n2),其中 n 是專案的數量。
演算法
Step 1: Set MIN to location 0 in the array. Step 2: Search the minimum element in the list. Step 3: Swap with value at location MIN. Step 4: Increment MIN to point to next element. Step 5: Repeat until list is sorted.
示例
import java.util.Arrays;
public class SelectionSort {
public static void main(String args[]) {
int myArray[] = {10, 20, 25, 63, 96, 57};
int n = myArray.length;
System.out.println("Contents of the array before sorting : ");
System.out.println(Arrays.toString(myArray));
for (int i=0 ;i< n-1; i++) {
int min = i;
for (int j = i+1; j<n; j++) {
if (myArray[j] < myArray[min]) {
min = j;
}
}
int temp = myArray[min];
myArray[min] = myArray[i];
myArray[i] = temp;
}
System.out.println("Contents of the array after sorting : ");
System.out.println(Arrays.toString(myArray));
}
}
輸出
Contents of the array before sorting : [10, 20, 25, 63, 96, 57] Contents of the array after sorting : [10, 20, 25, 57, 63, 96]
廣告