日期:2014-05-20 浏览次数:20685 次
public class SortTest { public static void main(String[] args) { int[] array = new int[] { 5, 1, 6, 4, 7, 3, 2 }; println(array); // insertSort(array); // chooseSort(array); // bubbleSort(array); sort(array); } // 1.冒泡排序 static void bubbleSort(int[] array) { if (array == null) { return; } for (int i = 1; i < array.length; i++) { System.out.println("-----i=" + i + "-----"); for (int j = 0; j < array.length - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; println(array); } } } } // 2.选择排序 static void chooseSort(int[] array) { if (array == null) { return; } for (int i = 0; i < array.length; i++) { System.out.println("-----i=" + i + "-----"); int temp = array[i]; int smallIndex = i; for (int j = i + 1; j < array.length; j++) { if (temp > array[j]) { temp = array[j]; smallIndex = j; } } array[smallIndex] = array[i]; array[i] = temp; println(array); } } // 3.插入排序 static void insertSort(int[] array) { if (array == null) { return; } for (int i = 0; i < array.length; i++) { int temp = array[i]; int index = i; for (int j = i - 1; j >= 0; j--) { if (temp < array[j]) { array[j + 1] = array[j]; index = j; } } array[index] = temp; println(array); } } // 4. static void sort(int[] array) { if (array == null) { return; } for (int i = 0; i < array.length; i++) { System.out.println("-----i=" + i + "-----"); for (int j = 0; j < i; j++) { if (array[i] < array[j]) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } println(array); } } static void println(int[] array) { if (array == null) { return; } for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); } }