Home >Web Front-end >JS Tutorial >Sharing of three sorting algorithms in js_javascript skills

Sharing of three sorting algorithms in js_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:50:461224browse
Copy code The code is as follows:

/**
* Value exchange operation
* arr The array being operated
* i The index value of the element being operated
* j The distance between the two elements being operated
*/
function refer(arr , i, j){
var change = (arr[i] - arr[i - j]) < 0 ? true : false, value;
if (change) {
value = arr[ i];
arr[i] = arr[i - j];
arr[i - j] = value;
return arguments.callee(arr, i - j, j);
}
else {
return arr;
}
}
//Insertion sort
function insert(array){
for (var i = 1, len = array. length; i < len; i ) {
if (array[i] < array[i - 1]) {
refer(array, i, 1);
}
}
return array;
}

The above part is insertion sort, then Hill sort:
Copy code The code is as follows:

//Hill sort
function shell(array){
var length = array.length, value;
for ( var i = Math.floor(length / 2); i > 0; i = Math.floor(i / 2)) {
for (var j = i; j < length; j ) {
if (array[j] < array[j - i]) {
refer(array, j, i);
}
else {
continue;
}
}
}
return array;
}

The refer method used in the two methods is the same method. Finally, merge sort:
Copy code The code is as follows:

//Merge sort
function order(arr1, arr2){
var arrLong = arr1.length > arr2.length ? arr1 : arr2;
var arrShort = arr1.length <= arr2.length ? arr1 : arr2
var arr = [];
for (var i = 0, l = arrShort.length; i < l; i ) {
for (var j = 0, len = arrLong.length; j < len; j ) {
if (arrShort[i] < arrLong[j]) {
arr.push(arrShort[i]);
if (i == l - 1) {
for (var m = 0, n = arrLong.length; m < n; m ) {
arr[arr.length] = arrLong[m];
}
break;
  }
else {
arr.push(arrLong[j]);
arrLong.shift();
continue;
}
}
}
return arr;
}

Students who have good suggestions can leave a message! No need to go into details here, just look at the code.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn