java排序高級之選擇排序實現(xiàn)方法
本文實例講述了java排序高級之選擇排序實現(xiàn)方法。分享給大家供大家參考。具體如下:
選擇排序(Selection sort)是一種簡單直觀的排序算法。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再從剩余未排序元素中繼續(xù)尋找最?。ù螅┰兀缓蠓诺揭雅判蛐蛄械哪┪?。以此類推,直到所有元素均排序完畢。
選擇排序的主要優(yōu)點與數(shù)據(jù)移動有關。如果某個元素位于正確的最終位置上,則它不會被移動。選擇排序每次交換一對元素,它們當中至少有一個將被移到其最終位置上,因此對n個元素的表進行排序總共進行至多n-1次交換。在所有的完全依靠交換去移動元素的排序方法中,選擇排序屬于非常好的一種。
最差時間復雜度 О(n²)
最優(yōu)時間復雜度 О(n²)
平均時間復雜度 О(n²)
最差空間復雜度 О(n) total, O(1) auxiliary
代碼實現(xiàn):
package com.baobaotao.test; /** * 排序研究 * */ public class Sort { /** * 選擇排序 * @param array 數(shù)組 */ public static void selectSort(int[] array) { int length = array.length ; int index = 0 ; for(int i=0;i<length-1;i++) { index = i ; for(int j=i+1;j<length;j++) { if(array[j] < array[index]) { index = j ; } } swap(array, i, index) ; printArr(array) ; } } /** * 按從小到大的順序交換數(shù)組 * @param a 傳入的數(shù)組 * @param b 傳入的要交換的數(shù)b * @param c 傳入的要交換的數(shù)c */ public static void swap(int[] a, int b, int c) { if(b == c) return ; int temp = a[b] ; a[b] = a[c] ; a[c] = temp ; } /** * 打印數(shù)組 * @param array */ public static void printArr(int[] array) { for(int c : array) { System.out.print(c + " "); } System.out.println(); } public static void main(String[] args) { int[] number={11,95,45,15,78,84,51,24,12} ; selectSort(number) ; } }
輸出:
11 95 45 15 78 84 51 24 12 11 12 45 15 78 84 51 24 95 11 12 15 45 78 84 51 24 95 11 12 15 24 78 84 51 45 95 11 12 15 24 45 84 51 78 95 11 12 15 24 45 51 84 78 95 11 12 15 24 45 51 78 84 95 11 12 15 24 45 51 78 84 95
希望本文所述對大家的java程序設計有所幫助。
相關文章
SpringBoot項目報錯:"Error?starting?ApplicationContext....
這篇文章主要給大家介紹了關于SpringBoot項目報錯:“Error?starting?ApplicationContext.?To?display?the?conditions?report?re-run?...”的解決辦法,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2022-08-08SpringBoot 策略模式實現(xiàn)切換上傳文件模式
策略模式是指有一定行動內容的相對穩(wěn)定的策略名稱,這篇文章主要介紹了SpringBoot 策略模式 切換上傳文件模式,需要的朋友可以參考下2023-11-11MyBatis 實現(xiàn)批量插入和刪除中雙層循環(huán)的寫法案例
這篇文章主要介紹了MyBatis 實現(xiàn)批量插入和刪除中雙層循環(huán)的寫法案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01