【算法实作】各种冒泡算法实现
作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/
package org.bupt.test; import java.util.ArrayList; class MyResource { ArrayList<Integer> arrList= new ArrayList<Integer>(); public MyResource(ArrayList<Integer> arrList) { this.arrList = arrList; } public void insertionSort() { boolean conFlag = true; for (int i = 0; i < arrList.size(); i++) { while (conFlag) {//每趟比较前先判断上次比较是不是没有互换动作发生,若是则说明剩下没有排的已经满足顺序 conFlag =false; for (int j = 0; j < arrList.size()-i-1; j++) { if (arrList.get(j)<arrList.get(j+1)) { int temp = arrList.get(j); arrList.set(j, arrList.get(j+1)); arrList.set(j+1, temp); conFlag = true; } } 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(); } }
有序区和无序区冒泡排序:
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(); } }