Summary of sorting and array deduplication in js algorithms _ javascript tips-js tutorial

Source: Internet
Author: User
It is relatively simple to implement array sorting in js by using the sort method in the array. The following is a good example. You can refer to how to implement array sorting in js, using the sort method in the array is relatively simple:

I. Sorting

Simple array sorting

The Code is as follows:


Var arr = [];
For (var I = 0; I <20; I ++ ){
Arr. push (Math. floor (Math. random () * 100 ))
}
Arr. sort (function (a, B ){
Return a> B? 1:-1;
})
Alert (arr)


You cannot simply use the sort method. By default, the sort method is sorted in ascii alphabetic order, rather than the number size,

The sort () method can accept a method as a parameter. This method has two parameters. Represent the two array items for each sort comparison. In sort () sorting, this parameter is executed every time two array items are compared, and the two compared arrays are

Item is passed to this function as a parameter. When the return value of the function is 1, the order of two array items is exchanged. Otherwise, the order is not exchanged.

Array sorting of Algorithms

The Code is as follows:


Var arr = [];
For (var I = 0; I <20; I ++ ){
Arr. push (Math. floor (Math. random () * 100 ))
}
// Generate an unordered arr Array
Function sort (arr, start, end ){
// The array length is 1.
If (start = end ){
Return [arr [start]
} Else if (start = end-1 ){
// The array length is 2, which is sorted by the value size.
If (arr [start]> arr [end]) {
Return [arr [end], arr [start]
} Else {
Return [arr [start], arr [end]
}
}
// The array length is half
Var l = Math. floor (start + end)/2 );
// Array on the left
Var arrLeft = sort (arr, start, l );
// Array on the right
Var arrRight = sort (arr, l + 1, end );
// Return results
Var result = [];
// Split the two arrays into two parts. The two arrays only compare the first number in the array. If the value is small, the system places the value in the result and deletes the small value, fixed by the shift method in the array. When no data exists in the array on the left or the array on the right
// Use concat to merge the result array with the array with other data, and return the result.
While (arrLeft. length> 0 | arrRight. length> 0 ){
If (arrLeft. length = 0 ){
Result = result. concat (arrRight );
Break;
} Else if (arrRight. length = 0 ){
Result = result. concat (arrLeft );
Break;
}
If (arrLeft [0] result. push (arrLeft. shift ())
} Else {
Result. push (arrRight. shift ());
}
}
Return result;
}
Var arrSort = sort (arr, 0, arr. length-1); // parameter array, starting position, ending position

Document. write (arr +'
'+ ArrSort );


Explanation: array sorting mainly involves splitting an array into two until it cannot be. In the end, only one or two Arrays can be removed, because the array length can be an odd or even number, split to the final array, only one or two of the results are sorted and returned, and the results are combined in a one-to-one comparison. This method may be difficult for everyone to think about. Is it true that we have always adopted the first one? But there is still a word about performance in the world, when the data comes after dozens of hundreds or even hundreds, there is no difference in the result time calculated by everyone, if we still have the confidence to use the first method when the data volume is several hundred million or billions, in fact, the js algorithm is divide and conquer, and many problems are divided into small ones to solve.

2. remove duplicates from Arrays

Simple Method to remove duplicates: declare an empty array first, insert the repeated array for loop, and repeat the non-repeated inserts.

The Code is as follows:


Var arr = [];
For (var I = 0; I <20; I ++ ){
Arr. push (parseInt (Math. random () * 10 ));
}
Array. prototype. indexOf = function (n ){
For (var I = 0; I If (this [I] = n ){
Return I;
}
}
Return-1;
}
Function removeDup (arr ){
Var result = [];
For (var I = 0; I if (result. indexOf (arr [I]) =-1 ){

Result. push (arr [I]);
}
}
Return result;
}
Var arr2 = removeDup (arr)
Document. write (arr +'
'+ Arr2)


Remove duplicate algorithm Arrays

The Code is as follows:


Var arr = [];
For (var I = 0; I <20; I ++ ){
Arr. push (parseInt (Math. random () * 10 ));
}
Array. prototype. indexOf = function (n ){
For (var I = 0; I If (this [I] = n ){
Return I;
}
}
Return-1;
}
Function removeDup (arr, s, e ){
If (s = e ){
// Split to one
Return [arr [s]
} Else if (s = E-1 ){
// You do not need to separate the remaining two parts for optimization.
If (arr [s] = arr [e]) {
Return [arr [s]
} Else {
Return [arr [s], arr [e];
}
}
// Divide the array into two segments,
Var l = Math. floor (s + e)/2 );
// Left
Var arrL = removeDup (arr, s, l );
// Right
Var arrR = removeDup (arr, l + 1, e );
// Copy the result to the left first.
Var result = arrL;
// Insert non-repeated data into the result cyclically
For (var I = 0; I if (result. indexOf (arrR [I]) =-1) result. push (arrR [I])
}
Return result; // return result
}
Var arrDup = removeDup (arr, 0, arr. length-1 );
Document. write (arr +'
'+ ArrDup );


Explanation:Split the repeated array into one or two arrays, and put the data on the left in the result. Duplicate inserts are skipped on the right until the loop is complete, you can return the result.
Related Article

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.