排序算法Java实现——选择排序(直接选择排序)

来源:互联网 发布:进入国外网站软件 编辑:程序博客网 时间:2024/06/05 21:07

比较排序代码:


/*@(#)chooseSort.java   2017-4-22  * Copy Right 2017 Bank of Communications Co.Ltd. * All Copyright Reserved */package com.sort.cn;/** * TODO Document chooseSort * <p> * @version 1.0.0,2017-4-22 * @author Singit * @since 1.0.0 */public class chooseSort {//选择排序    public static void main(String[] args) {        int[] arr={1,3,2,45,65,33,12};        System.out.println("交换之前:");        for(int num:arr){            System.out.print(num+" ");        }                //选择排序的优化        for(int i = 0; i < arr.length - 1; i++) {// 做第i趟排序            int k = i;            for(int j = k + 1; j < arr.length; j++){// 选最小的记录                if(arr[j] < arr[k]){                     k = j; //记下目前找到的最小值所在的位置                }            }            //在内层循环结束,也就是找到本轮循环的最小的数以后,再进行交换            if(i != k){  //交换a[i]和a[k]                int temp = arr[i];                arr[i] = arr[k];                arr[k] = temp;            }            }        System.out.println();        System.out.println("交换后:");        for(int num:arr){            System.out.print(num+" ");        }    }}

输出结果:

交换之前:1 3 2 45 65 33 12 交换后:1 2 3 12 33 45 65 


直接选择排序代码:

public static void main(String[] args) {        int[] a = { 2, 5, 5, 3, 9, 6, 1, 4, 8, 7 };        select_sort(a);        print_array(a);}    public static void select_sort(int[] a) {        for (int i = 0; i < a.length; i++) {            for (int j = i + 1; j < a.length; j++) {                if (a[i] > a[j]) {                    swap(a, i, j);                }            }        }}    public static void swap(int[] a, int b, int c) {        if (b == c)            return;        a[b] = a[b] ^ a[c];        a[c] = a[b] ^ a[c];        a[b] = a[b] ^ a[c];    }    public static void print_array(int[] a) {        if (a.length == 0)            return;        for (int i : a) {            System.out.print(i + " ");        }}


输出结果:

1 2 3 4 5 5 6 7 8 9 


1 0