java冒泡排序和插入算法的简单使用

1.一组乱序的字符序列m、b、p、f、a、u、z,请用冒泡排序算法,使之按字母表顺序排列


public class Work1 {

	public static void main(String[] args) {
		char[] num1 = { 'm', 'b', 'p', 'f', 'a', 'u', 'z' };
		for (int i = 0; i < num1.length; i++) {
			boolean f = false;// 判断是否进行了数据移动
			for (int j = 0; j < num1.length - 1 - i; j++) {

				if (num1[j] > num1[j + 1]) {// 将更小的数放在后面
					char temp = num1[j];
					num1[j] = num1[j + 1];
					num1[j + 1] = temp;
					f = true;
				}
			}
			if (!f) {
				// 没有在比较了直接结束
				break;
			}
		}

		for (char i : num1) {
			System.out.print(i + " ");
		}

	}

}

 

 

2.一组有序的字符序列a、b、c、e、f、p、u、z,向次字符序列中插入一个新的字符,要求插入之后字符序列仍保持有序

​

public class Work2 {

	public static void main(String[] args) {
		char[] num = { 'a', 'b', 'c', 'e', 'f', 'p', 'u', 'z', 0 };
		char num1 = 'h';
		int index = num.length - 1;
		for (int i = 0; i < num.length; i++) {
			if (num[i] > num1) {
				index = i;// 找到插入节点下标,并停止运行
				break;
			}
		}

		for (int i = num.length - 2; i >= index; i--) {// 将插入点以后的字符向后移动
			num[i + 1] = num[i];
		}
		num[index] = num1;// 将字符插入
		for (char i : num) {
			System.out.print(i + " ");
		}
	}

}

​

 

 3.判断一个数组是否有序

​

public class Work3 {
	public static void main(String[] ages) {
		int[] num = { 4, 8, 10, 25, 26, 35, 45 };
		int cunt = 0;
		int cm = 0;
		for (int i = 0; i < num.length - 1; i++) {

			if (num[i] > num[i + 1]) {
				cunt++;// 降序数组计数器
			} else {
				cm++;// 升序数组计数器
			}
		}
		// 判断计数器是否达到次数,都不达到则此数组无序
		if (cunt == num.length - 1) {
			System.out.print("此数组是降序数组");
		} else if (cm == num.length - 1) {
			System.out.print("此数组是升序数组");
		} else {
			System.out.print("此数组不是有序数组");
		}
	}

}

​

 4.插入排序

//插入排序
public class Text4 {
	public static void main(String[] ages) {
		int[] num = { 54, 154, 84, 24, 1, 53, 8, 158 };
	
		int temp=0;
		int j=0;
		for (int i = 1; i < num.length; i++) {
			temp=num[i];
			for ( j = i - 1; j >= 0; j--) {
				if (temp > num[j]) {
					break;
				}else {
					
					num[j+1]=num[j];
				
					
				}
			}
			num[j+1]=temp;
		}
		for(int i:num) {
			System.out.print(i+" ");
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值