选择排序

.

[color=green]context:

1.图片show by pictures

2.源码source code
[/color]

[color=red]有图有真相:[/color]

[color=red]第一轮:[/color]

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

[color=red]第二轮:[/color]

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

[color=red]第三轮:[/color]

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

[color=red]源码部分:[/color]



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[10];
// 初始化数组
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[targetIndex] > array[tempIndex]) {
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[oneIndex];
array[oneIndex] = array[anotherIndex];
array[anotherIndex] = tempValue;
}

// 初始化数组:使用随机数为数组赋值
private static int[] initArray(int[] array) {
Random random = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(100) - random.nextInt(100);
}
System.out.println("原数组:" + Arrays.toString(array));
return array;
}

}




[color=red]输出结果:[/color]



原数组:[52, -58, 8, -49, 45, -53, 9, 56, -1, -17]
排序后的数组:[-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]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值