New technologies are constantly changing, and mastering some of the basics is a solid foundation for future learning technologies that are constantly being updated. Recently have nothing to do, in order to brush up on the previous data structure, the structure of the sorting algorithm with JS implementation, and at the end of this article embedded demo.
Simple sort
Bubble sort
Bubble sort is the simplest sort algorithm, the time complexity of n squared, the code is as follows:
function Bubblesort (array) {for
(var i = 0; i < Array.Length; i++) {for
(var j = array.length; j > 0; j--) {
if (Array[j] < array[j-1]) {
var temp = array[j-1];
ARRAY[J-1] = array[j];
ARRAY[J] = temp;
}
}
/* Output result */document.write ("This is the first + (i + 1) +" secondary cycle ·, the result is: "); for (var k = 0; K < Array.Length; k++) {
document.write (Array[k] + ",");
}
document.write ("<br/>");
/* Output end/
}
}
Direct Insert Sort
The direct insertion sort also belongs to the simple sort algorithm, the time complexity is also n squared, but the performance is slightly better than bubble sort, the code is as follows:
function Insertsort (array) {
var temp;
for (var i = 1; i < Array.Length i++) {
var temp = array[i];
for (var j = i; j > 0 && Temp < array[j-1]; j--) {
array[j] = array[j-1];
}
ARRAY[J] = temp
/* Output result */document.write ("cap? + i + "all over the sort result is:") for (var n = 0; n < Array.Length; n++) {
document.write (Array[n] + ",");
}
document.write ("<br/>")/
* output end/
}
}
Select sort
Selection is also a simple sorting algorithm, the time complexity is also n squared, performance is also slightly better than bubble sort, the code is as follows:
function Selectsort (array) {
var min, temp;;
for (var i = 0; i < Array.Length; i++) {
min = i;
for (var j = i + 1; j < Array.Length; J + +) {
if (Array[min] > Array[j])
min = j;
}
if (min!= i) {
temp = array[i];
Array[i] = array[min];
Array[min] = temp;
}
/* Output result */document.write ("the first + i +" all over the order of the result is: ") for (var n = 0; n < Array.Length; n++) {
document.write (Array[n] + ",");
}
document.write ("<br/>")/
* output end/
}
}