選擇排序java實現
阿新 • • 發佈:2018-12-13
package algorithm; public class SelectSort { public static void main(String[] args) { int[] a = {6,2,5,4,7,1,3,9,8}; selectSort(a, a.length); // selectSort2(a); for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } /** * 找出最大數的下標 * @param a * @return */ private static int findMaxPostion(int[] a, int n){ int max = a[0]; int pos = 0; for (int i = 0; i < n; i++) { if(a[i] > max){ max = a[i]; pos = i; } } return pos; } /** * 找出每次比較數的最大值跟陣列的最後一個元素進行交換 * @param a * @param n */ private static void selectSort(int[] a,int n){ while(n > 1){ int postion = findMaxPostion(a,n); int temp = a[postion]; a[postion] = a[n-1]; a[n-1] = temp; n--; } } private static void selectSort2(int[] a){ for (int i = 0,k = 0; i < a.length; i++,k = i) { for (int j = i+1; j < a.length; j++) { if(a[k] > a[j]){ k = j; } } if(i != k){ int temp = a[i]; a[i] = a[k]; a[k] = temp; } } } }