选择排序
What
选择排序(Selection Sort),是一种简单直观的排序算法,基本上一说到排序就会想到的方法。其思想是:遍历数组,每次找到最大(或最小)的值。
How
Java代码
//测试类
public class Test {
public static void main(String []args) {
int[] array = {1,9,8,2,7,3,4,6,5};
int[] afterSortedArray = Selection.sort(array);
for ( int i : afterSortedArray ) {
System.out.println(i);
}
}
}
class Selection{
//排序算法:对int[]数组降序排序
public static int[] sort(int[] array) {
//数组长度
int length = array.length;
//循环遍历数组
for ( int i = 0 ; i < length-1 ; i ++ ) {
//temp用来记录最大值(或最小值)下标
int temp = i;
for ( int j = i+1 ; j < length ; j ++ ) {
//找到更大(或更小)的值,改变temp
if ( array[temp] < array[j] ) {
temp = j;
}
}
//temp最大值的小标不变,无需交换
if ( temp == i ) continue;
//swap value
array[i] = array[i] + array[temp];
array[temp] = array[i] - array[temp];
array[i] = array[i] - array[temp];
}
return array;
}
}
When & Where
什么时候使用?
个人理解:主要理解其思想,在一些无法使用Array.sort(),Comparator等情况下,对小量数据进行排序,因为其简单,所以代码也会相对不那么复杂。
结束语:优秀是一种习惯
1958

被折叠的 条评论
为什么被折叠?



