选择排序:
如何理解?
1. 在长度为N的无序数组中,第一次遍历n-1个数,找到最小的数值与第一个元素交换;
2. 第二次遍历n-2个数,找到最小的数值与第二个元素交换;
3. ....
4.第n-1次遍历,找到最小的数值与第n-1个元素交换,排序完成。
实现代码:
package com.temp;
/**
* 选择排序
* @author Mr.L
*
*/
public class B {
public static void select_sort(int array[],int lenth){
for(int i=0;i<lenth-1;i++){
int minIndex = i;
for(int j=i+1;j<lenth;j++){
if(array[j]<array[minIndex]){
minIndex = j;
}
}
if(minIndex != i){
int temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
//输出
for (int k = 0; k <array.length; k++) {
System.out.println(array[k]);
}
}
public static void main(String[] args) {
// 创建数组 赋值
int [] array= {1,3,2,8,6};
// 调用 5 数组长度+1
select_sort(array, array.length);
}
}
输出: