演算法(1) 選擇排序演算法 java
阿新 • • 發佈:2018-11-14
簡介:選擇排序是一個時間複雜度為O(N^2)的基本排序演算法,當然也有其適用的場景,比如說該演算法的易於實現的特性,可應用於對某些實際問題的快速實現上.
原理:從未排序的資料中,選出最小的資料,然後與未排序的第一個資料進行比較交換操作,直到所有的資料都排好序.
步驟:
①在未進行排序的資料中,尋找到最小的資料,假設為A,並記錄下該下標
②用未排序的第一個資料B與從①中得到的資料A進行比較,如果A小於B,則交換A與B,否則不交換.
③重複以上的①②步驟,直到所有的資料都排好序.
程式碼是思路的體現,因此在寫程式碼之前一定要理清楚思路.
/** * 規則 [0,i-1] 採用前閉後閉的原則進行演算法的編寫,牢記. 順序為 從小到大排序 * * @author JamesWang * */ public class SelectionSort implements IPerformance { private int[] arr; public SelectionSort(int[] arr) { this.arr = arr; } @Override public void performance() { int minIndex; for (int i = 0; i <= arr.length - 1; i++) {// [0,arr.length - 1] 前閉 後閉 minIndex = i;// 預設當前i為最小值的下標 for (int j = i + 1; j <= arr.length - 1; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } //進行比較交換操作 if(arr[minIndex] != arr[i]) {//只有當兩個下標對應的值不相等再進行交換 arr[i] = arr[i] + arr[minIndex]; arr[minIndex] = arr[i] - arr[minIndex]; arr[i] = arr[i] - arr[minIndex]; } } } /** * 測試 * @param args */ public static void main(String[] args) { int[] arr = SortUtils.createArray(100);//建立一個數值範圍為[0,100)包含有100個元素的陣列 PerformanceUtils performanceUtils = new PerformanceUtils(new SelectionSort(arr));//建立代理類 performanceUtils.performance();//執行代理方法 System.out.println(SortUtils.getString(arr)); } }
public interface IPerformance {
public void performance();
}
public class SortUtils { public static int[] createArray(int count) { int[] arr = new int[count]; Random random = new Random(); for (int index = 0; index < count; index++) { arr[index] = random.nextInt(count); } return arr; } public static int[] copy(int[] arr) { return Arrays.copyOf(arr, arr.length); } public static String getString(int[] arr) { StringBuffer sb = new StringBuffer(); for(int a : arr) { sb.append( a + ","); } return sb.toString(); } }
/** * 使用代理模式來進行效能的測試 * * @author JamesWang Create on 2018年1月4日 下午4:05:35 */ public class PerformanceUtils implements IPerformance { private IPerformance performance; public PerformanceUtils(IPerformance performance) { this.performance = performance; } @Override public void performance() { long startTime = System.currentTimeMillis(); performance.performance(); System.out.println("執行時間為:" + (System.currentTimeMillis() - startTime) + "毫秒"); } }