选择排序、冒泡排序和插入排序

1.选择排序

在这里插入图片描述
2.冒泡排序

for (int i = 0; i < array.length - time; i++) {
				int current = array[i];
				int next = array[i + 1];
				if (current > next) {
					array[i] = next;
					array[i + 1] = current;
				}
			} 

每进行一次这个循环 ,每相邻的俩个数就会比较一次,如果前面的数字比后面的数字大,就调换位置。最后结果:每次将最大的那个值,放在最后一位。

package west;

public class Test {

	public static void main(String[] args) {
		int [] array = {1,2,4,5,3};
		
		
		for (int time = 1; time <= array.length-1; time++) {   //总共5个数,需要遍历四次,四次最大值放后面
			for (int i = 0; i < array.length - time; i++) {     //每次最大值放后面之后,那么最后那几位数字就不需要再进行比较了,这样就减少比较次数,减少运行次数
				int current = array[i];
				int next = array[i + 1];
				if (current > next) {
					array[i] = next;
					array[i + 1] = current;
				}
			} 
		}
	}
}

冒泡排序示意图:
在这里插入图片描述
3.插入排序:

package west;

public class Test {

	public static void main(String[] args) {
		int [] array = {1,2,4,5,3};
		
		for (int i = 1; i < array.length; i++) {   //只将数组的第一个数字,作为有效的遍历区间,其他数据都是待插入的数据
			int data = array[i];
			int j = 0;
			for (; j < i; j++) {
				if (array[j] > data) {
					break;
				}
			}
			//j=2
			for (int k = i; k > j; k--) {
				array[k] = array[k - 1];
			}
			array[j] = data;
		}
		for (int a : array) {
			System.out.println(a);
		} 
	}
}

每一次插入一个数字,比如要插入最后一个数字3:
①将数字3的位置找到:找到待插入的位置,遍历之前的有序区间(前四个数),如果是升序排序,那就找到一个比3这个数字大的数据所在的位置
②做移动:将找到位置后的元素往后移动一位
③将待插入的数字插入到该数组就行
插入排序示意图:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值