冒泡双向排序

来源:互联网 发布:卖域名的 编辑:程序博客网 时间:2024/05/16 15:49

转载请注明出处:http://blog.csdn.net/droyon/article/details/8785903

/** * 双向冒泡排序,从左向右冒泡排序,大数沉底,然后从右向左排序,小数冒泡。如此循环。 * @author  * */public class BubbleTwoSort {private static int[] array = new int[]{1,8,2,9,3,7,11,23,90,4,5};public static void main(String args[]){        System.out.println("排序前");        printArray();        System.out.println("\n排序后");        bubbingTwoSort();        printArray(); } private static void bubbingTwoSort(){ int temp; int left=0; int right=array.length-1; int index=0; while(left <= right){ index++; for(int i=left;i<right;i++){ if(array[i]>array[i+1]){ temp = array[i]; array[i] = array[i+1]; array[i+1] = temp; } } //想看没一趟交换结果,打开下面输出 /*System.out.println("第"+index+"次正向冒泡"); printArray(); System.out.println();*/ right--; for(int j=right;j>left;j--){ if(array[j]<array[j-1]){ temp = array[j]; array[j]=array[j-1]; array[j-1] = temp; } } left++; //查看输出,打开以下输出 /*System.out.println("第"+index+"次反向冒泡"); printArray(); System.out.println();*/ } } public static void printArray(){          for(int i=0;i<array.length;i++){              System.out.print(array[i]+"   ");          }   }  }


输出结果:

排序前1   8   2   9   3   7   11   23   90   4   5   排序后1   2   3   4   5   7   8   9   11   23   90   

原创粉丝点击