Java排序算法之 —— 选择排序
package algorithm.sort;/** * 选择排序:首先找出数组中的最小元素,将其与数组的第一个元素交换, * 接着找出次小元素,将其与数组的第二个元素交换 * 对数组中的前n-1个元素执行这一过程 * @author Administrator * */public class SelectSort {//对数组指定的元素进行排序public void selectSort(int[] a, int from, int end) {int minIndex; //记录最小元素的索引for (int i = from; i <= end; i++) {minIndex = i;//首先假设最小元素为每次循环的第一个元素for(int j = i+1; j <= end; j++) {if(a[j] < a[minIndex])minIndex = j;//找出最小元素对应的索引}//交换最小元素与每次循环的第一个元素exchange(a, i, minIndex);}}//对整个数组排序public void selectSort(int[] a) {selectSort(a, 0, a.length-1);}//交换数组中的两个元素public void exchange(int[] a, int i, int j) {int temp = a[i];a[i] = a[j];a[j] = temp;}//打印数组public void printArr(String str, int[] a) {System.out.print(str + "\t");for(int i = 0; i < a.length; i++)System.out.print(a[i] + " ");System.out.println();}//测试数据public static void main(String[] args) {SelectSort ss = new SelectSort();int[] a = {1,4,3,7,5,8,0};ss.printArr("原始数组为:", a);ss.selectSort(a);ss.printArr("合并排序后:", a);}}