选择排序算法

来源:互联网 发布:韩国虚拟手机号软件 编辑:程序博客网 时间:2024/05/22 16:05
package cn.xingxing.datastructure.sort;import java.util.Scanner;/** *<pre> 从待排序的数据元素集合中选取关键字最小的的数据元素并将它与原始数据元素集合中的第一个数据元素交换位置; * 然后从不包过第一个位置的数据元素集合中选取关键字最小的数据元素并将它与原始数据集合中的第二个数据元素交换位置; * 如此重复,直到数据元素集合中只剩下一个数据元素为止 * 初始关键字排序 64 5 7 89 6 24 * 第一次排序: [5] 64 7 89 6 24 * 第2次排序: [5 6] 64 7 89 24 * 第3次排序: [5 6 7] 24 64 89 * 第4次排序:[5 6 7 24] 64 89 *  第4次排序:[5 6 7 24 64] 89 *  第4次排序:[5 6 7 24] 64 89] *  </pre> * @author duanxingxing * */public class SelectSort {public static void selectSort(int[] a) {for (int i = 0; i < a.length - 1; i++) {int temp = a[i];int small = i;/** *  j < a.length 因为要比较到最后一个元素 */for (int j = i + 1; j < a.length; j++) {if (a[small] > a[j])small = j;}//如果是最后一个元素就不用排序(省得自己和自己交换)if (small != i) {a[i] = a[small];a[small] = temp;}}for (int b : a) {System.out.println(b);}}/** * @param args */public static void main(String[] args) {// 从键盘读入数据Scanner sc = new Scanner(System.in);int[] a = new int[6];int i = 0;System.out.println("请输入要排序的int整数!");while (sc.hasNext()) {a[i] = sc.nextInt();i++;if (i >= 6)break;}sc.close();selectSort(a);}}