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

比较排序代码:


/*@(#)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 


  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值