Bubble SortingAlgorithm(Java)
I. Summary
The day before yesterday, someone asked about the implementation of the Sorting Algorithm, so I took the time to write a Bubble Sorting Algorithm. The principle of the Bubble Sorting Algorithm is to compare the current number with each subsequent number starting from the first number. If the current number is greater than any subsequent number, both switch the positions of the current two numbers. When the data size is small, the efficiency of the Bubble Sorting Algorithm is still acceptable (10000 Length Integer array sorting is about 351 ms), but the efficiency of Bubble Sorting is relatively low when the array size is relatively long, you can use Quick Sort or merge.
II,Code
The key code of the bubble algorithm is as follows:
Package COM. csdn. algorithm; import Java. util. random;/*** test the Bubble Sorting ** @ author administrator **/public class testbubblesort {/*** @ Param ARGs */public static void main (string [] ARGs) {// 1. construct the data random arandom = new random (); int narraylenght = 60000; int [] aData = new int [narraylenght]; for (INT I = 0; I <aData. length; I ++) {aData [I] = arandom. nextint (10000);} // 2. long lstarttime = system. currenttimemillis (); int [] asortresult = bubblesort (aData); long lendtime = system. currenttimemillis (); // 3. system. out. println ("sorting [" + narraylenght + "] count," + (lendtime-lstarttime) + "Ms"); // 3. print the result // For (INT I = 0; I <asortresult. length; I ++) {// system. out. println (asortresult [I]); //}/*** sort the input integer array in bubble order, and sort the array in ascending order. <br/> * algorithm complexity: O (N ^ 2) <br/> * arrays with less than 10000 data won't time out (about one second) <br/> * But if it is larger, it is necessary to use the quick sort or merge O (N * log2 (n )) ** @ Param _ aintegerarray * @ return */Private Static int [] bubblesort (INT [] _ aintegerarray) {// 1. parameter verification if (_ aintegerarray = NULL) {return _ aintegerarray;} // 2. starting from the first number, compare the numbers one by one with the numbers one by one, and take a small value for (INT I = 0; I <_ aintegerarray. length; I ++) {for (Int J = I + 1; j <_ aintegerarray. length; j ++) {If (_ aintegerarray [I]> _ aintegerarray [J]) {// exchange two numbers int ntemp = _ aintegerarray [I]; _ aintegerarray [I] = _ aintegerarray [J]; _ aintegerarray [J] = ntemp ;}}// 3. return Value return _ aintegerarray ;}}
Iii. execution time statistics
| sorting [10] count, with a time of 0 Ms sort [100] times, 1 Ms sort the number of [1000, it takes 3 Ms sort [10000] times, 351 Ms sort [20000] times, 1326 Ms sort [30000] times, 2714 Ms sort [60000] times, it takes 9054 Ms Program to test |