插入排序,冒泡排序,选择排序

插入排序,冒泡排序,选择排序

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

三大排序的基本内容


一、选择排序

1.原理

在一组数组中,0-n-1的范围内遍历找到一个最小值,将其与0位置的值进行交换,使得最小值在0位置,0位置有序,然后在1-n-1的范围内继续重复此步骤。具体过程如下

数组0 数组n-1 数组1 数组2 取得最小值跟0位置进行交换,0位置有序 取得最小值跟1位置进行交换,0——1位置有序 取得最小值跟2位置进行交换,0——2位置有序 数组0 数组n-1 数组1 数组2

按照此过程,依次将数组排序,这就是选择排序

2.代码实现

package Base;
//选择排序
public class Code02 {
    public static void swap(int[] arr,int i,int j){
        int temp = arr[j];
        arr[j] = arr[i];
        arr[i] = temp;
    }
    public static void selectSort(int[] nums){
        //判断一下临界条件
        if (nums == null || nums.length < 2){
            return;
        }
        //因为头一直变化,所以给定一个变量i
        int N = nums.length;
        for (int i = 0; i < N; i++){//这个循环用来实现范围,在其中查找最小值
            int minIndex = i;
            for (int j = i + 1; j < N; j++){
                minIndex = nums[j] < nums[minIndex] ? j : minIndex;
            }//这里找出了最小值
            //进行交换
            swap(nums,i,minIndex);
        }
    }
    public static void show(int[] nums){
        for (int i = 0; i < nums.length; i++){
            System.out.print(nums[i] + " "  );
        }
        System.out.println();
    }
    public static void main(String[] args) {
        int[] nums = {2,3,8,1};
        show(nums);
        selectSort(nums);
        show(nums);
    }
}

二、冒泡排序

1.原理

在一组数组中,数据之间两两进行比较。一轮比较过后,得到一个最大值,放到了末尾。重复此过程,得到最终结果。
0—n-1
0—n–2
0—n-3
所以定义一个end

2.代码实现

 public static void boubleSort(int[] nums){
        //判断一下临界条件
        if (nums == null || nums.length < 2){
            return;
        }
        //冒泡排序
        int N = nums.length;
        for (int end = N - 1;end >= 0; end --){
            for (int second = 1; second <= end;  second++){
            //这里的1是0123456数组的下标,表示第二个
                if (nums[second - 1] > nums[second]){
                    swap(nums,second-1,second);
                }
            }
        }

    }

三、插入排序

1.原理

插入排序是这三大排序里面最好的。插入排序顾名思义就是将一个数插入数组中,使其有序。类似我们斗地主时插入牌的方法。
0-0有序
0-1有序
0-2将2插入其中,与0,1比较。
0–n-1

2.代码实现

public static void insertSort(int[] nums){
        //判断一下临界条件
        if (nums == null || nums.length < 2){
            return;
        }
        //插入排序
        int N = nums.length;
        for (int end = 1; end < N; end++){
            int newIndex = end;
            while (newIndex - 1 >= 0 && nums[newIndex-1] > nums[newIndex]){
                swap(nums,newIndex-1,newIndex);
                newIndex--;
            }
        }

    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值