Bubble SortingThe time complexity is O (n ^ 2), which has two advantages:
1. "programming complexity" is very low and easy to writeCode;
2. stability. The stability here means that the relative sequence of the same elements in the original sequence is still maintained to the sorted sequence, but the heap sorting and quick sorting are not stable.
The basic idea of implementation: Bubble Sorting is completed by n-1 sort sub-sorting. The number of I sort sub-sorting ranges from 1st to n-I, if the number of I is greater than the number of the last one (ascending or descending), two numbers are exchanged.
<SCRIPT type = "text/JavaScript"> var number = new array (); For (VAR I = 0; I <1000; I ++) {number [I] = parseint (999 * Math. random ();} function bubblingsort (Num) {var K; // compare node for (var j = num. length-1; j> 0; j --) {for (VAR I = 0; I <j; I ++) {If (Num [I]> num [I + 1]) {k = num [I]; num [I] = num [I + 1]; num [I + 1] = K ;}} return num;} document. write ("original order:" + number + "<br/>"); document. write ("sort order:" + bubblingsort (number); </SCRIPT>
Insert sort (Insertion sort) Algorithm Description is a simple and intuitive sorting algorithm. Its working principle is to build an ordered sequence. For unordered data, scan the sorted sequence from the back to the front, locate the corresponding position, and insert it. Insert sorting usually uses in-place sorting (that is, sorting of the extra space of O (1). Therefore, during the scanning from the back to the forward, the sorted elements need to be moved backward repeatedly to provide the insert space for the new elements. When the sequence is basically ordered, it is the optimal time complexity and the fastest sorting algorithm.
<SCRIPT type = "text/JavaScript"> function insert_sort (Num) {var key; For (VAR I = 1; I <num. length; I ++) {key = num [I]; j = I-1; while (j> = 0 & num [J]> key) {num [J + 1] = num [J]; j --;} num [J + 1] = key;} return num;} var number = new array (); for (VAR I = 0; I <1000; I ++) {number [I] = parseint (1000 * Math. random ();} document. write (insert_sort (number); </SCRIPT>