选择排序
选择排序从理解上可以当作两个数组储存来理解:
我先定义一个无序数组{11,23,155,156,32,33,88,42},一个有序数组{}
依次从无序数组中取出最小的一个元素放进有序数组中
{11,},{23,155,156,32,33,88,42}
{11,23},{155,156,32,33,88,42}
{11,23,32},{155,156,33,88,42}
{11,23,32,33},{155,156,88,42}
{11,23,32,33,42},{155,156,88}
{11,23,32,33,42,88},{155,156}
{11,23,32,33,42,88,155},{156}
{11,23,32,33,42,88,155,156},{}
代码如下
public class selectionSort {
public static void main(String[] args) {
//原始无序数组
int [] number = {11,23,155,156,32,33,88,42};
//默认从number[0]开始,循环number.length-1次
for (int i = 0; i < number.length-1; i++) {
//定义最小的序列
int minIndex = i;
int j;
//循环没有比较过的的数
for (j = i+1; j < number.length; j++) {
//如果当前数比前一个大则交换当前数与前一个数的序列
if (number[j]<number[minIndex]){
minIndex=j;
}
}
//交换序列后进行值的交换
int temp = number[minIndex];
number[minIndex] = number[i];
number[i] = temp;
}
for (int i = 0; i < number.length; i++) {
System.out.println(number[i]);
}
}
}