运行结果:
=================================================
代码部分:
=================================================
/java_test/src/com/b510/sort/BubbleSort.java
1 package com.b510.sort; 2 3 4 5 /** 6 * 冒泡法排序 7 * @author Administrator 8 * 9 */ 10 public class BubbleSort { 11 12 //升序和降序 13 private static final int DES = 0; 14 private static final int DESC = 1; 15 16 /** 17 * 交换一个数组中的两个值,即:array[i]和array[j]的值进行交换 18 * @param array 原数组 19 * @param i 数组下标i 20 * @param j 数组下标j 21 * @return 交换后的新数组 22 */ 23 public int[] swap(int[] array,int i,int j){ 24 array[i] = array[i] + array[j]; 25 array[j] = array[i] - array[j]; 26 array[i] = array[i] - array[j]; 27 return array; 28 } 29 30 /** 31 * 使用冒泡排序方法进行排序 32 * @param array 原数组 33 * @param des 升序为DES,降序为DESC 34 * @return 新数组 35 */ 36 public int[] bubbleSort(int[] array,int des){ 37 for(int i = 0 ;i < array.length - 1; i++){ 38 for(int j = array.length -1 ; j > i ; j --){ 39 if(des == DES){ 40 //降序排序 41 //第一轮:第一个和其他比较,如果有比第一个大的,就放在第一个的位置; 42 //第二轮:第二个和其他比较(除第一个),如果有比第二个大的,就放在第二个的位置; 43 //以此下去 44 if(array[j] < array[i]){ 45 swap(array, i, j); 46 } 47 }else{ 48 //升序排序 49 if(array[j] > array[i]){ 50 swap(array, i, j); 51 } 52 } 53 } 54 } 55 return array; 56 } 57 58 /** 59 * 获取一个随机数组 60 * @param from 随机数最小值 61 * @param to 随机数最大值 62 * @param number 生成数量 63 * @return 随机数组 64 */ 65 public int[] getRandomArray(int from,int to,int number){ 66 int[] array = new int[number]; 67 for(int i =0;i < number ; i++){ 68 array[i] = from + (int) (Math.random() * (to - from + 1)); 69 System.out.println("array["+i+"] = " + array[i]); 70 } 71 return array; 72 } 73 74 /** 75 * 显示信息 76 * @param array 77 */ 78 public void showInfo(int[] array){ 79 System.out.println("排序后的情况:"); 80 for(int i = 0; i < array.length ; i++){ 81 System.out.println("array["+i+"] = " + array[i]); 82 } 83 } 84 85 /** 86 * test 87 * @param args 88 */ 89 public static void main(String[] args) { 90 BubbleSort bubbleSort = new BubbleSort(); 91 int[] result = bubbleSort.bubbleSort(bubbleSort.getRandomArray(10, 200, 5), DESC); 92 bubbleSort.showInfo(result); 93 } 94 }
看到这里,是不是很简单啊....