首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java排序算法之 —— 取舍排序

2013-01-08 
Java排序算法之 —— 选择排序package algorithm.sort/** * 选择排序:首先找出数组中的最小元素,将其与数组

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);}}


//output~
原始数组为:1 4 3 7 5 8 0
合并排序后:0 1 3 4 5 7 8

热点排行