栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

三种排序法(冒泡,选择,插入)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

三种排序法(冒泡,选择,插入)

目录

1.冒泡

2.选择

3.插入


1.冒泡

其原理外层循环控制循环次数,内层循环拿出相邻的两个数比较

package ffyc.com.shuzu.firsthw;

import java.util.Arrays;

public class MaoPao {
    public static void main(String[] args) {

        int []a=new int[]{3,2,5,7,57,1,87,78};
        int t=0;
        for (int i = 0; i < a.length-1; i++) {
            for (int j = 0; j < a.length-1-i; j++) {
                while(a[j]>a[j+1]){
                    t=a[j];
                    a[j]=a[j+1];
                    a[j+1]=t;
                }
            }
        }
        System.out.println(Arrays.toString(a));

    }
}
2.选择

其原理外层控制循环次数,内层控制循环制造比较的数

package ffyc.com.shuzu.firsthw;

import java.util.Arrays;

public class XuanZe {
    public static void main(String[] args) {

        int []a=new int[]{3,2,45,64,23,43,77,98,66};
        int t=0;
        for (int i = 0; i < a.length-1; i++) {
            for (int j = i+1; j < a.length; j++) {
                while (a[i]>a[j]){
                    t=a[i];
                    a[i]=a[j];
                    a[j]=t;

                }
            }
            System.out.println(Arrays.toString(a));
        }
    }
}

3.插入

其原理先拿出索引为1的数去与其前一个数比较

package ffyc.com.shuzu.firsthw;

import java.util.Arrays;

//拿索引为一的数,用这个数去比较
public class Insert {
    public static void main(String[] args) {
        int[] nums = new int[]{3, 5, 8, 2, 1};
        for (int i = 1; i < nums.length; i++) {
            int temp = nums[i];
            for (int j = i - 1; j >= 0; j--) {
                if (nums[j] > temp) {
                    nums[j + 1] = nums[j];
                    nums[j] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(nums));
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/827530.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号