排序中冒泡排序是最好理解的,每次都是拿一个元素与其他所有元素进行比较,知道此元素放置到合理位置,紧接着对其相邻的下一个元素反复执行此操作,知道所有元素都执行一遍,最终得到的就是排序要的数组。
public class BubbleSort { public void bubbleSort(int[] pArray) { if (pArray == null) { throw new NullPointerException(); } // 数组中有n个元素,循环n次 for (int i = 0; i < pArray.length-1; i++) { // 数组中当前一个元素与其他n-1个元素进行比较 for (int j = 0; j < pArray.length-i-1; j++) { if ( pArray[j] > pArray[j+1] ) { swap(pArray, j, j+1); } } } } /** * 交换数组中的两个值 */ private void swap(int[] pArray, int pX, int pY) { int temp = pArray[pX]; pArray[pX] = pArray[pY]; pArray[pY] = temp; } }
测试使用的main方法
public static void main(String[] args) { int[] arr = {3, 5, 1, 10, 0, 100, 3, 9}; BubbleSort bubbleSort = new BubbleSort(); bubbleSort.bubbleSort(arr); for (int i = 0; i < arr.length; i++) { System.out.println("value = "+ arr[i]); } }
* 另外一种写法,{3, 5, 1, 10, 0, 100, 3, 9} , 排序规则是从左向右值是依次递增(即左侧的值都小于右侧的值)
public void bubbleSortTwo(int[] pArray) { if (pArray == null) { throw new NullPointerException(); } for (int i = 0; i < pArray.length; i++) { // i的左侧是已经排序好的 for (int j = i + 1; j < pArray.length; j++) { if ( pArray[i] > pArray[j] ) { swap(pArray, i, j); } } } }
public void bubbleSortThree(int[] pArray) { if (pArray == null) { throw new NullPointerException(); } for (int i = pArray.length - 1; i >= 0; i--) { // i的右侧是已经排序好的 for (int j = pArray.length - 1; j >= i; j--) { if ( pArray[i] > pArray[j] ) { swap(pArray, i, j); } } } }
时间复杂度:1+2+3+ ...... +(n-1) = n*(n-1)/2 = O(N平方)
最好情况:O(n)只需比较判断一次就结束
最坏情况:O(n平方)
空间复杂度:O(1) 因为未使用辅助空间
参考资料:
<< 返回 蛙步学排序算法 - 索引