ocaicai 发表于 2013-1-27 13:05:08

选择排序

.

context:

1.图片show by pictures

2.源码source code


有图有真相:

第一轮:

http://dl.iteye.com/upload/picture/pic/89056/41e4d764-27ca-3eb0-87ad-402461f0291e.jpg

第二轮:

http://dl.iteye.com/upload/picture/pic/89054/74722e31-00f9-332d-85b1-7458bf09afe5.jpg

第三轮:

http://dl.iteye.com/upload/picture/pic/89052/526fab78-787b-3a87-b040-8060720a380e.jpg

源码部分:

package sortAlgorithem;import java.util.Arrays;import java.util.Random;/** ** @author ocaicai@yeah.net @date: 2011-5-1 值得注意的都在详细的注释里面了 */public class SelectSortTest {public static void main(String[] args) {// 定义一个数组int[] emptyArray = new int;// 初始化数组int[] targetArray = initArray(emptyArray);// 打印最后的数组System.out.println("排序后的数组:" + Arrays.toString(selectSort(targetArray)));}private static int[] selectSort(int[] array) {// totalTurns总共比较的次数比数组的长度少1,比如:数组长度为2时只需比较1次int totalTurns = array.length - 1;// countedTurns:已经比较了的轮数for (int countedTurns = 0; countedTurns < totalTurns; countedTurns++) {// 临时的索引用来记录每一轮比较结果的目的(最大或者最小)索引,每一轮都从第一个位置0开始int tempIndex = 0;// 每一次临时的都从目标的第一个开始比较for (int targetIndex = 0; targetIndex < array.length - countedTurns; targetIndex++) {// 如果目标索引处的值比临时索引处的值大,那么将此索引赋值给临时索引if (array > array) {tempIndex = targetIndex;}}// 一轮比较完后才进行临时索引(实际上是最大或者最小值的索引了)和最高处交换值swapTwoIndexValue(array, tempIndex, array.length - 1 - countedTurns);}return array;}/** * function:交换两索引处的值 ** @param array * @param oneIndex * @param anotherIndex */private static void swapTwoIndexValue(int[] array, int oneIndex,int anotherIndex) {int tempValue = array;array = array;array = tempValue;}// 初始化数组:使用随机数为数组赋值private static int[] initArray(int[] array) {Random random = new Random();for (int i = 0; i < array.length; i++) {array = random.nextInt(100) - random.nextInt(100);}System.out.println("原数组:" + Arrays.toString(array));return array;}}

输出结果:

原数组:排序后的数组:[-58, -53, -49, -17, -1, 8, 9, 45, 52, 56]原数组:[-61, -22, -1, 9, 24, -14, -8, -24, 77, 60]排序后的数组:[-61, -24, -22, -14, -8, -1, 9, 24, 60, 77]
页: [1]
查看完整版本: 选择排序