常见算法学习及其Java实现--有序区和无序区的冒泡算法实现

package org.bupt.test; import java.util.ArrayList; class MyResource { ArrayList<Integer> arrList= new ArrayList<Integer>(); public MyResource(ArrayList<Integer> arrList) { this.arrList = arrList; } /* 分为有序区和无序区,起初整个数组均为无序区,flag为有序区的端点,其左边是无序区,右边是有序区 * 记录了最后一次发生互换的地方,那么右边就是有序区 */ public void insertionSort() { int index = arrList.size()-1;//起初有序区端点为最后一个,也就是有序区个数为0 while (index > 0) { int flag = index ;//有序区的端点暂时保存在flag中 index = 0;//人为认定现在有序区为整个数组,也就是说排序完成。 for (int i = 0; i < flag; i++) {//无序区进行排序 if (arrList.get(i)<arrList.get(i+1)) {//两两比较,发现有不符合左>右的情况则互换 int temp = arrList.get(i); arrList.set(i, arrList.get(i+1)); arrList.set(i+1, temp); index = i;//记录发生互换的位置作为有序区的端点 } } /*说明情况所用的打印代码*/ for (int j = 0; j < arrList.size(); j++) { System.out.print(arrList.get(j)+" "); } System.out.println(""); } } public void printOut() { for (int i = 0; i < 9; i++) { System.out.print(arrList.get(i)+" "); } } } public class Main { public static void main(String args[]) throws Exception { ArrayList<Integer> arrList = new ArrayList<Integer>(); for (int i = 0; i < 9; i++) { arrList.add(new Integer((int) (Math.random()*100))); System.out.print(arrList.get(i)+" "); } System.out.println(""); MyResource mtMyResource = new MyResource(arrList); mtMyResource.insertionSort(); mtMyResource.printOut(); } }

输出:

50 84 70 74 33 90 98 54 99
84 70 74 50 90 98 54 99 33
84 74 70 90 98 54 99 50 33
84 74 90 98 70 99 54 50 33
84 90 98 74 99 70 54 50 33
90 98 84 99 74 70 54 50 33
98 90 99 84 74 70 54 50 33
98 99 90 84 74 70 54 50 33
99 98 90 84 74 70 54 50 33
99 98 90 84 74 70 54 50 33

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值