![]() The first method simply launches the recursive subroutine recMergeSort, which performs the sorting of the array. The first two methods are the MergeSort and the recMergeSort methods. ![]() #Xcom 2 war of the chosen research order codeNow let’s look atthe code for performing a MergeSort. The algorithm uses two extra loops that are called only if one or the other of the two arrays still has data in it after the main loop finishes. But what if one array runs out of data before the other? Because this is likely to happen, the algorithm makes provisions for this situation. The smaller element is added to the third array, and this process continues until both arrays run out of data. The element not added to the third array is then compared to the next element in the other array. The merge process compares the first two elements of each data set (stored in temporary arrays), copying the smaller value to yet another array. Then the two sets are merged, resulting in 2 29 31 54 58 71 77 78. Then each half is sorted to give 29 54 58 71 and 2 31 77 78. First, the data set is broken P1: IWV 0521547652c14 CB820-McMillan-v1 Ap18:46 286 ADVANCED SORTING ALGORITHMS up into two separate sets: 71 54 58 29 and 31 78 2 77. Let’s say we have the following data in the set: 71 54 58 29 31 78 2 77. ![]() The easy work comes when sorting the data set. When the two halves are sorted, they are brought together using a merge routine. This algorithm works by breaking up the data set into two halves and recursively sorting each half. ![]() MERGESORT ALGORITHM The MergeSort algorithm exemplifies a recursive algorithm. P1: IWV 0521547652c14 CB820-McMillan-v1 Ap18:46 284 ADVANCED SORTING ALGORITHMS good increment to use is based on the code fragment While (h 0) For outer=hTonumElements - 1 temp = arr(outer) inner = outer While (inner>h-1 AndAlso arr(inner - h) >= temp) arr(inner) = arr(inner - h) inner -= h End While arr(inner) = temp Next h=(h-1)/3 End While End Sub P1: IWV 0521547652c14 CB820-McMillan-v1 Ap18:46 MergeSort Algorithm 285 Here’s some code to test the algorithm: Sub Main() Const SIZE As Integer = 19 Dim theArray As New CArray(SIZE) Dim index As Integer For index=0ToSIZE theArray.Insert(Int(100 * Rnd() + 1)) Next Console.WriteLine() theArray.showArray() Console.WriteLine() theArray.ShellSort() theArray.showArray() Console.Read() End Sub The output from this code looks like this: The ShellSort is often considered a good advanced sorting algorithm to use because of its fairly easy implementation, but its performance is acceptable even for data sets in the tens of thousands of elements. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |