Sharing of three sort algorithms in js

Source: Internet
Author: User

Copy codeThe Code is as follows:
/**
* Value exchange operation
* Array to which arr is operated
* I index value of the operated Element
* J Distance between the two elements 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;
}
}
// Insert sorting
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 section is insert sorting, followed by hill sorting:
Copy codeThe Code is as follows:
// Sort by hill
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 Sorting:
Copy codeThe Code is as follows:
// Merge and 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;
}

If you have good suggestions, you can leave a message! I will not go into detail here. Let's take a look at the code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.