選擇排序算法
工作原理:
每一次從待排序的數(shù)據(jù)元素中選中最小的一個元素,然后,再從剩余未排序元素中繼續(xù)尋找最小元素,將2個元素交換位置,就達(dá)到了已排序的元素一直是從小到大了。
這個算法的時間復(fù)雜度為O(n2),空間復(fù)雜度為O(1)。文章來源:http://www.zghlxwxcb.cn/news/detail-458952.html
/**
* @Author: 翰林猿
* @Description:選擇排序
**/
public class Select {
? ?public Select() {
? }
?
? ?public static void SelectionSort(int[] arr) {
? ? ? ?//i: 當(dāng)前位置 j: 從當(dāng)前位置開始增加的變量(用于從當(dāng)前位置開始遍歷,減少遍歷量)
? ? ? ?for (int i = 0; i < arr.length; i++) { ? ? ?//遍歷數(shù)組,發(fā)現(xiàn)最小的,與當(dāng)前的交換
? ? ? ? ? ?int min_index = i; ? ? ? ? ? ? ? ? ? ? ?//用于記錄最小項的下標(biāo)
? ? ? ? ? ?for (int j = i; j < arr.length; j++) { ?//從當(dāng)前位置開始遍歷,找到最小的
? ? ? ? ? ? ? ?if (arr[min_index] > arr[j]) { ? ? ? //如果最小項大于j處項
? ? ? ? ? ? ? ? ? ?min_index = j;
? ? ? ? ? ? ? }
? ? ? ? ? }
? ? ? ? ? ?//到此為止,我們已經(jīng)找到了比當(dāng)前位置i小的最小項,將二者交換即可。
? ? ? ? ? ?swap(min_index, i, arr);
? ? ? }
? }
?
? ?public static void swap(int min_index, int i, int[] arr) { ?
? ? ? ?int t = arr[min_index];
? ? ? ?arr[min_index] = arr[i];
? ? ? ?arr[i] = t;
? }
?
? ?public static void main(String[] args) {
? ? ? ?int[] arr = {1, 8, 9, 7, 3, 5, 6};
? ? ? ?Select.SelectionSort(arr);
? ? ? ?for (int it : arr) {
? ? ? ? ? ?System.out.println(it);
? ? ? }
? }
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-458952.html
/**
* @Author: 翰林猿
* @Description:選擇排序
**/
public class Select {
? ?public Select() {
? }
?
? ?public static <E extends Comparable<E>>void SelectionSort(E[] arr) { ? ? ? ?
? ? ? ?//i: 當(dāng)前位置 j: 從當(dāng)前位置開始增加的變量(用于從當(dāng)前位置開始遍歷,減少遍歷量)
? ? ? ?for (int i = 0; i < arr.length; i++) { ? ? ? ? ? ? ?//遍歷數(shù)組,發(fā)現(xiàn)最小的,與當(dāng)前的交換
? ? ? ? ? ?int min_index = i; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//用于記錄最小項的下標(biāo)
? ? ? ? ? ?for (int j = i; j < arr.length; j++) { ? ? ? ? ?//從當(dāng)前位置開始遍歷,找到最小的
? ? ? ? ? ? ? ?if (arr[min_index].compareTo(arr[j]) < 0) { ? ? ? //如果最小項大于j處項
? ? ? ? ? ? ? ? ? ?min_index = j;
? ? ? ? ? ? ? }
? ? ? ? ? }
? ? ? ? ? ?//到此為止,我們已經(jīng)找到了比當(dāng)前位置i小的最小項,將二者交換即可。
? ? ? ? ? ?swap(min_index, i, arr);
? ? ? }
? }
?
? ?public static <E> void swap(int min_index, int i, E[] arr) {
? ? ? ?E t = arr[min_index];
? ? ? ?arr[min_index] = arr[i];
? ? ? ?arr[i] = t;
? }
?
? ?public static void main(String[] args) {
? ? ? ?Integer[] arr = {1, 8, 9, 7, 3, 5, 6};
? ? ? ?Select.SelectionSort(arr);
? ? ? ?for (int it : arr) {
? ? ? ? ? ?System.out.println(it);
? ? ? }
? }
}
到了這里,關(guān)于選擇排序算法之泛型優(yōu)化的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!