I won’t say much nonsense, I will just post the code to you. The specific code is as follows:
var array = [1,2,3,4,5]; // --> Service//Efficiency---> The most efficient is for an ordered array//Flag true false for(var j = 0; j < array.length - 1;j++ ){//- j Reduce the number of comparisons after each sorting is completed var isTrue = true; //If the array itself is in ascending order, directly output for(var i = 0; i < array.length - j - 1;i++){if(array[i] > array[i+1]){var temp = array[i];array[i] = array[i+1];array[i+1] = temp;isTrue = false;}}document.write(array);if(isTrue){break;}} var array = [12,34,4,6,20];//length - 1 j = 0 - length - 1for(var j = 0; j < array.length - 1;j++){var min = array[j]; // 1 3 34 4 345 5var minIndex = j;for(var i = j + 1; i < array.length;i++){if(array[i] < min){min = array[i];minIndex = i;}}if(minIndex != j){var temp = array[minIndex];array[minIndex] = array[j];array[j] = temp;}}Let’s take a look at the code that implements three sorts of Javascript: bubble sort, select sort, and insert sort
<script type="text/javascript"> var a; a = [66, 53, 11, 5, 4, 3, 2, 1]; /*Bubble sort*/ (function maopaopaixu() { for (var i = 0; i < a.length - 1; i++) {//The number of comparisons is length-1 for (var j = 0; j < a.length - 1 - i; j++) { if (a[j] > a[j + 1]) { var tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } alert(a); })(); a = [66, 53, 11, 5, 4, 3, 2, 1]; /*Select sort*/ (function xuanzepaixu() { var min/*The index of the smallest item*/, tmp; for (var out = 0; out < a.length - 1; out++) {//The number of comparisons is length-1 min = out; for (var inner = out + 1; inner < a.length; inner++) {//This is a.length, not a.lenght-1, because the latter will cause the second right-digit to fail to participate in the sorting. if (a[inner] < a[min]) { min = inner; } //Move the smallest item to the left tmp = a[out]; a[out] = a[min] a[min] = tmp; } } alert(a); })(); a = [66, 53, 11, 5, 4, 3, 2, 1]; /*Insert sort*/ (function charupaixu() { for (var out = 1; out < a.length; out++) { var tmp = a[out]; var inner = out; while (a[inner - 1] > tmp) { a[inner] = a[inner - 1]; --inner; } a[inner] = tmp; } alert(a); })(); </script>The above is the implementation code for JavaScript bubble sorting and selection sorting introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time!