|
 |  | Section 7: Sorting Array Data | |
|
|
You are in Section 7 of 9, Article 7.3 of 7.5
Merge Sort
A merge sort can be used to combine two previously sorted arrays into a third array. The third array will remain sorted.
A merge sort requires two arrays that have been previously sorted into ascending or descending order. When the sort first begins (for ascending order), the first elements of each of the arrays are evaluated to see which array contains the smaller value. Once the smaller value is found, it will be placed as the first element in the third array.
The sort continues to evaluate the elements of both arrays until the end of one of the arrays is reached. Depending on which array has been completely searched, the remaining values in the other array will be attached to the end of the third array.
Algorithm Illustration:
Assume we have the following two integer arrays:
| Array 1 |
| 1 |
| 5 |
| 11 |
| 22 |
| 35 |
| 41 |
| 52 |
|
|
|
Here are the results after the first comparison:
| Array 1 |
| 1 |
| 5 |
| 11 |
| 22 |
| 35 |
| 41 |
| 52 |
|
|
|
|
|
After the second comparison:
| Array 1 |
1 |
| 5 |
| 11 |
| 22 |
| 35 |
| 41 |
| 52 |
|
|
|
|
|
After the third comparison:
| Array 1 |
1 |
| 5 |
| 11 |
| 22 |
| 35 |
| 41 |
| 52 |
|
|
|
|
|
This process is repeated until all elements in both arrays have been placed into the third array.
Example: Merging Into Ascending Order
The following is a complete program demonstrating the merge sort algorithm to merge two arrays previously sorted into ascending order.
It makes use of the following mergeSort function:
Study the complete program:
Example: Merging Into Descending Order
The following complete program demonstrates how to merge two arrays previously sorted into descending order:
The following complete program demonstrates how to merge two arrays previously sorted into ascending order. The values of both arrays are specified by the user at run-time, a sort routine is executed on each array, and then a merge routine will be executed to merge the two arrays.
At this point, we've covered the selection, bubble, and merge sort. Sometimes, an array may need to appear sorted when it is actually not. Is this possible?
A standard technique for solving this type of problem is called the tag sort.
Read on for more...
Next: Tag Sort
You are in Section 7 of 9, Article 7.3 of 7.5
[Back to Top]
|
|
|
|

|