选择排序.

选择排序
/**
 * 思路:2, 6, 3, 8, 4, 9, 7
 *   1:2, 6, 3, 8, 4, 9, 7   先确定第一位最小的
 *   2:2, 3, 6, 8, 4, 9, 7   先确定第二位最小的
 *   3:2, 3, 4, 8, 6, 9, 7   .....
 *   4:2, 3, 4, 6, 8, 9, 7
 *   5:2, 3, 4, 6, 7, 9, 8
 *   6:2, 3, 4, 6, 7, 8, 9
 *
 *   每次先拿外围循环的循环位(i)与内循环的的外循环+1(i+1)开始比较
 *   选出最小的与外循环的循环位交换位置
 *   交换之后的最小数据不参与比较
 *
 *
 */
public class SelectSort {
    public static void main(String[] args) {
        int[] a = {2, 6, 3, 8, 4, 9, 7};
        int len = a.length;
        for (int i = 0; i < len-1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < len; j++) {
                //拿到单次循环里的最小值
                minIndex = a[j] < a[minIndex] ? j : minIndex;
            }
            //把最小值放到第一位
            swap(a, i, minIndex);
        }
        System.out.println(Arrays.toString(a));

        String str1 = new StringBuilder("计算机").append("软件").toString();
        String str6 = new StringBuilder("计算机").append("软件").toString();
        String str7 = str6.intern();
        String str2 = str1.intern();
        String str5 = "计算机软件";
        String str3 = new StringBuilder("ja").append("va").toString();
        String str4 = str3.intern();
        System.out.println(str2==str5); //t
        System.out.println(str1==str2); //f
        System.out.println(str3==str4); //f
        System.out.println(str2==str6); //t
        System.out.println(str1==str6); //f
        System.out.println(str2==str7); //t
    }

    private static void swap(int[] a, int i, int minIndex) {
        //把i 和 minIndex 交换
//        a[i] = a[i] ^ a[minIndex];   //错误的,前提是不能是一块地址 这里的i和minIndex是一个
//        a[minIndex] = a[i] ^ a[minIndex];  //a[i]
//        a[i] = a[i] ^ a[minIndex];  //a[minIndex]
        int tmp = a[i];
        a[i] = a[minIndex];
        a[minIndex] = tmp;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值