二 选择排序

来源:互联网 发布:mysql select count 编辑:程序博客网 时间:2024/06/07 10:41

选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法(比如序列[5, 5, 3]第一次就将第一个[5]与[3]交换,导致第一个5挪动到第二个5后面)。

java代码

/** * 选择排序 * */public class SelectionSort {/** * 排序算法 * */public static void sort(int array[]){if( array == null || array.length == 0 ){return ;}int temp;for(int i = 0 ; i < array.length ; i++ ){for(int j = i+1  ; j < array.length ; j++ ){if( array[i] > array[j] ){temp = array[i];array[i] = array[j];array[j] = temp;}}}}/** * 输出数组 * */public static void show(int array[]){if( array == null || array.length == 0 ){return ;}for(int i = 0 ; i < array.length ; i++){System.out.print( array[i] +" ");}}/** * main函数进行测试 * */public static void main(String[] args) {int array[] = {1,23,42,533,52,32,11,1,32,3242,234,223,795,96,234567};SelectionSort.sort(array);SelectionSort.show(array);}}