冒泡排序
package foo; public class Main { public static void bubbleSort(int[] a, int len) { int in, out; for (out = len - 1; out > 0; --out) { for (in = 0; in < out; ++in) { if (a[in] > a[in+1]) { swap(a, in, in + 1); } } } } public static void swap(int[] a, int index1, int index2) { int temp = a[index1]; a[index1] = a[index2]; a[index2] = temp; } public static void main(String[] args) { int[] a = new int[] {3, 2, 1, 5, 4}; bubbleSort(a, a.length); } }
冒泡排序的效率O(N*N),比较N*N/2,交换N*N/4