Sort Algorithm code in JavaScript

Source: Internet
Author: User

The data item used as the sort basis is called the "Sort code", that is, the key code of the data element. To facilitate searching, we usually want data tables in the computer to be sorted by key codes. For example, the semi-query of an ordered table is more efficient. In addition, the construction process of the binary sorting tree, B-tree, and B + tree is a sorting process. If the key code is the primary key code, the result obtained after sorting is unique for any sequence to be sorted. If the key code is a secondary key code, the sorting result may not be unique, this is because the data elements with the same key code cannot maintain the positional relationship between these elements in the sorting results and before sorting.
If you use a sorting method to sort any data element sequence by key code: if the location relationship between the elements of the same key code is the same before and after sorting, this sorting method is stable, but not necessarily consistent.
There are two types of sorting: inner sorting and outer sorting.
Inner sorting: refers to the sorting process in which the columns to be sorted are fully stored in the memory. It is suitable for element sequences that are not very large.
External sorting: it refers to the external memory that needs to be accessed during the sorting process. An element sequence that is large enough can only be used because it cannot be fully stored in the memory.

Now we paste the JavaScript Implementation of the three sorting algorithms.

The first is the simplest, which is the Bubble Sorting of individuals. Simply paste the code.Copy codeThe Code is as follows:/** @ name Bubble Sorting
* @ Lastmodify 2010/07/13
* @ Desc compare and sort
Complexity: O (n * n)
*/
Function BubbleSort (list ){
Var len = list. length;
Var cl, temp;
While (len --){
Cl = list. length;
While (cl --){
If (list [cl]> list [len] & cl <len ){
Temp = list [len];
List [len] = list [cl];
List [cl] = temp;
}
}
}
Return list;
}

Then there is the most common quick sorting, which is usually asked during interviews.Copy codeThe Code is as follows:/** @ name quick sorting
* @ Lastmodify 2010/07/14
* @ Desc compare and sort
Worst running time O (n * n );
Best run time O (nlogn)
*/
Function QuickSort (list ){
Var I = 0;
Var j = list. length;
Var len = j;
Var left;
Var right;
Var k = findK (I, j );
If (k! = 0 ){
Var leftArr = [];
Var rightArr = [];
Var midArr = [list [k];
While (len --){
If (len! = K ){
If (list [len]> list [k]) {
RightArr. push (list [len]);
}
Else {
LeftArr. push (list [len]);
}
}
}
Left = QuickSort (leftArr );
Right = QuickSort (rightArr );
List = left. concat (midArr). concat (right );
}
Return list;
}

Function findK (I, j ){
// The center of the query is found by default.
Return Math. floor (I + j)/2 );
}

The main idea of quick sorting is divide and conquer, which divides the sorted sequence into two parts, thus reducing the complexity of sorting. The clever use of recursion is also the subtlety of quick sorting. In the previous example, the findK function is used to find the "reference element". Other elements are compared with the findK function in sequence, and all the elements are placed in a set larger than the findK function, and then sort the two sets separately. The efficiency of quick sorting mainly depends on the implementation of findK functions and the degree of order of elements to be sorted. Therefore, quick sorting is an unstable sorting algorithm.

However, quick sorting is still a comparison-based sorting algorithm. All comparison-based sorting algorithms have a feature that, no matter how optimized, their average sorting time for an element set always increases with the increase in the number of elements in the set. Rather than comparing the sorting, this disadvantage is well overcome. They try to make the sorting time complexity tend to a number-independent stable value. The bucket sorting is representative. Let's take a look at its JavaScript implementation.Copy codeThe Code is as follows:/** @ name bucket sorting
* @ Author lebron
* @ Lastmodify 2010/07/15
* @ Desc non-Comparative sorting
*/
Function BucketSort (list ){
Var len = list. length;
Var range = findMax (list );
Var result = [],
Count = [];
Var I, j;
For (I = 0; I <range; I ++ ){
Count. push (0 );
}

For (j = 0; j <len; j ++ ){
Count [list [j] ++;
Result. push (0 );
}
For (I = 1; I <range; I ++ ){
Count [I] = count [I-1] + count [I];
}
For (j = len-1; j> = 0; j --){
Result [count [list [j] = list [j];
Count [list [j] --;
}
Return result;
}

Function findMax (list ){
Return MAX;
}

We can see that in the implementation of Bucket sorting, A findMax function is still used to determine the range of a large array, which is directly replaced by a constant MAX. First, initialize a large array of count with the length of MAX. Put the values in the sorted set into the corresponding position. For example, if an element value is 24, the 24th bits of count are marked as 1, and the result array length is + 1. Then calculate the position of the element whose count array won the log is 1 in the ranking of 1 in the entire count array. In this case, the value of the nth element in the count array should be its position after sorting, and n is the value corresponding to this position after sorting. Therefore, the key values in the count array are mapped to the result array one by one.
Bucket sorting cleverly utilizes this idea. If an element is n largest in a set, it should rank n digits, you don't need to worry about whether the former or the latter is bigger or smaller than it (no need to compare it ). Obviously, in actual conditions, the value range of elements in the sorted set may be much greater than the number of elements in the set. Therefore, you also need to allocate an array with a huge space. Therefore, the common scenario of Bucket sorting is in external sorting.

If you are interested, you can test the time consumption of the three sorting types in different orders of magnitude.

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.