This article mainly introduces two examples of Javascript sort algorithms for merging and sorting. For more information, see Merge sort) is an effective Sorting Algorithm Based on the merge operation. This algorithm is a very typical application of Divide and Conquer.
The Merge Sorting method combines two (or more) ordered tables into a new ordered table, that is, the sequence to be sorted is divided into several subsequences, each of which is ordered. Then combine the ordered subsequences into the overall ordered sequence.
Merge Sorting is an effective Sorting Algorithm Based on merge operations. This algorithm is a very typical application of Divide and Conquer. Merges ordered subsequences to obtain a fully ordered sequence. That is, first orders each subsequence, and then orders the subsequence segments. If two ordered tables are merged into an ordered table, it is called a 2-way merge.
The merge operation process is as follows:
1. Apply for a space so that the size is the sum of the two sorted sequences. This space is used to store the merged sequences.
2. Set two pointers. The initial position is the start position of the two sorted sequences respectively.
3. Compare the elements pointed to by the two pointers, select a relatively small element, and move the pointer to the next position.
4. Repeat Step 3 until a pointer reaches the end of the sequence.
5. Copy all the remaining elements of another sequence directly to the end of the merging sequence.
Example 1:
The Code is as follows:
/**
* A merge operation (merge) is an operation that combines two sorted sequences into one.
* The Merge Sorting Algorithm depends on the merge operation.
*
* The merging process is as follows:
*
* 1. Apply for a space to make it the sum of two sorted sequences. This space is used to store the merged sequence.
* 2. set two pointers. The initial position is the start position of the two sorted sequences respectively.
* 3. Compare the elements pointed to by the two pointers, select a relatively small element, and move the pointer to the next position.
* 4. Repeat Step 3 until a pointer reaches the end of the sequence.
* 5. Copy all the remaining elements of another sequence directly to the end of the merging sequence.
*
*/
Function mergeSort (items ){
If (items. length <2 ){
Return items;
}
Var middle = Math. floor (items. length/2 ),
Left = items. slice (0, middle ),
Right = items. slice (middle ),
Params = merge (mergeSort (left), mergeSort (right ));
Params. unshift (0, items. length );
Items. splice. apply (items, params );
Return items;
Function merge (left, right ){
Var result = [],
Il = 0,
Ir = 0;
While (il <left. length & ir <right. length ){
If (left [il] <right [ir]) {
Result. push (left [il ++]);
} Else {
Result. push (right [ir ++]);
}
}
Return result. concat (left. slice (il). concat (right. slice (ir ));
}
}
// Test
Var arr = [2, 1, 3, 12, 5, 66, 23, 87, 15, 32];
MergeSort (arr );
Example 2:
The Code is as follows: