[TOC]
Bubble Sort Program code
Package Com.uplooking.bigdata.datastructure;import Java.util.arrays;public class Bubblesort {public static void main (S Tring[] args) {int[] arr = {8,-2, 3, 9, 0, 1, 7, 6}; System.out.println ("Before sorting:" + arrays.tostring (arr)); Bubblesort (arr); System.out.println ("After sorting:" + arrays.tostring (arr)); /** * Sorting Process Analysis: * I previous comparison (Arr.length is 8) * Start: 8,-2, 3, 9, 0, 1, 7, 6 * * End of 1th trip:-2, 3, 8, 0, 1, 7, 6, 9 0 7 * * 2nd trip ended:-2, 3, 0, 1, 7, 6, 8, 9 1 6 * * End of 3rd trip:-2, 0, 1, 3, 6, 7, 8, 9 2 5 * * 4th trip Ends:-2, 0, 1, 3, 6, 7, 8, 9 3 4 * * End of 5th trip:-2, 0, 1, 3, 6, 7, 8, 9 4 3 * * 6th trip Ends:-2, 0, 1, 3, 6, 7, 8, 9 5 2 * * End of 7th trip:-2, 0, 1, 3, 6, 7, 8, 9 6 1 * * Conclusion: The number of trips to compare is arr.length-1 * Each trip needs to be compared Arr.len Gth-1-I times * * Because the bubble sort is reversed for each other, and does not change the order of its original sort, so it is stableSorting method */public static void Bubblesort (int[] arr) {for (int i = 0; i < arr.length-1; i++) {fo R (Int j = 0; J < arr.length-1-I; j + +) {if (Arr[j] > arr[j + 1]) {swap (arr, J, j + 1); }}}} public static void Swap (int[] arr, int i, int j) {Arr[i] = Arr[i] ^ arr[j]; ARR[J] = Arr[i] ^ arr[j]; Arr[i] = Arr[i] ^ arr[j]; }}
Test
排序前:[8, -2, 3, 9, 0, 1, 7, 6]排序后:[-2, 0, 1, 3, 6, 7, 8, 9]
Analysis of time complexity
1.可以看到,将比较次数相加起来(等差数列),其时间复杂度为O(n^2)2.由于冒泡排序为相邻两者相互比较对调,并不会更改其原本排序的顺序,所以是稳定排序法
Data structure and algorithms-bubble sort (Java implementation)