文章目錄
原理
每一次從待排序的數據元素中選出最小(或最大)的一個元素,存放在序列的起始位置,然後,再從剩餘未排序元素中繼續尋找最小(大)元素,然後放到已排序序列的末尾。以此類推,直到全部待排序的數據元素排完。 選擇排序是不穩定的排序方法
package exercise.array;
import java.util.Arrays;
public class SelectSort {
void selectSort(int[] arr){
for (int i = 0; i < arr.length; i++) {
int minIndex = findMinIndex(i,arr);
if (minIndex == i){
continue;
}
//最小的和當前的做交換
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
/**
*
* @param beginIndex 當前開始的尋找的索引
* @param arr 數組
* @return 返回從beginIndex開始查找,arr中最小的的數的索引
*/
int findMinIndex (int beginIndex,int[] arr){
int min = arr[beginIndex];
int minIndex = beginIndex;
for (int i = beginIndex; i <arr.length; i++) {
if (min>arr[i]){
min = arr[i];
minIndex = i;
}
}
return minIndex;
}
void print(int[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+"\t");
}
}
public static void main(String[] args) {
int[] arr = new int[]{7,5,1,2,4,6,10};
SelectSort selectSort = new SelectSort();
selectSort.selectSort(arr);
selectSort.print(arr);
}
}
input:
7,5,1,2,4,6,10
output:
1 2 4 5 6 7 10