标签:
1 package com.trfizeng.changesort; 2 3 /** 4 * @author trfizeng 内部排序 交换排序—冒泡排序(Bubble Sort) 5 */ 6 public class BubbleSort { 7 public static int[] bubbleSort(int[] array) { 8 if (array != null && array.length != 0) { 9 // 最外层循环控制需要多少趟 10 for (int i = 0; i < array.length; i++) { 11 // 内层循环控制每趟需要比较多少次,内循环走完时,最大的一个记录已经被挪到当前循环长度的末尾了,下一趟就劈开他不再跟他进行比较了,大数沉底了 12 for (int j = 0; j < array.length - i - 1; j++) { 13 // 如果发现后面的记录比当前记录大就进行交换 14 if (array[j] > array[j + 1]) { 15 int temp = array[j]; 16 array[j] = array[j + 1]; 17 array[j + 1] = temp; 18 } 19 } 20 } 21 } 22 return array; 23 } 24 }
1 package com.trfizeng.test; 2 3 import com.trfizeng.changesort.BubbleSort; 4 import com.trfizeng.insertionsort.StraightInsertionSort; 5 import com.trfizeng.selectionsort.SimpleSelectionSort; 6 7 /** 8 * 测试类 9 * 10 * @author trfizeng 11 * 12 */ 13 public class SortTest { 14 // 待排序数组 15 static int[] array = new int[] { 6, 1, 4, 10, 11, 8, 7, 1, 0 }; 16 17 /** 18 * 直接插入排序法测试 19 */ 20 public static void straightInsertionSortTest() { 21 System.out.print("待排序数组:[ "); 22 for (int i = 0; i < array.length; i++) { 23 System.out.print(array[i] + " "); 24 } 25 System.out.print("] "); 26 27 array = StraightInsertionSort.straightInsertionSort(array); 28 System.out.print("排好序的数组:[ "); 29 for (int i = 0; i < array.length; i++) { 30 System.out.print(array[i] + " "); 31 } 32 System.out.print("]"); 33 } 34 35 /** 36 * 选择排序 37 */ 38 public static void simpleSelectionSort() { 39 System.out.print("待排序数组:[ "); 40 for (int i = 0; i < array.length; i++) { 41 System.out.print(array[i] + " "); 42 } 43 System.out.print("] "); 44 45 array = SimpleSelectionSort.simpleSelectionSort(array); 46 System.out.print("排好序的数组:[ "); 47 for (int i = 0; i < array.length; i++) { 48 System.out.print(array[i] + " "); 49 } 50 System.out.print("]"); 51 } 52 53 /** 54 * 冒泡排序 55 */ 56 public static void bubbleSort() { 57 System.out.print("待排序数组:[ "); 58 for (int i = 0; i < array.length; i++) { 59 System.out.print(array[i] + " "); 60 } 61 System.out.print("] "); 62 63 array = BubbleSort.bubbleSort(array); 64 System.out.print("排好序的数组:[ "); 65 for (int i = 0; i < array.length; i++) { 66 System.out.print(array[i] + " "); 67 } 68 System.out.print("]"); 69 } 70 71 public static void main(String[] args) { 72 // SortTest.straightInsertionSortTest(); 73 74 // SortTest.simpleSelectionSort(); 75 76 SortTest.bubbleSort(); 77 } 78 }
标签:
原文地址:http://www.cnblogs.com/trfizeng/p/4307721.html