Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Implement the following algorithm in Java using an array of 10 random numbers. 172 Divide-and-Conquer 5.1 Mergesort Mergesort is a perfect example of a successful
Implement the following algorithm in Java using an array of 10 random numbers.
172 Divide-and-Conquer 5.1 Mergesort Mergesort is a perfect example of a successful application of the divide-and conquer technique. It sorts a given array A[0..n - 1] by dividing it into two halves AO..Ln/2] _ 1] and A[Ln/2]..n-1 sorting each of them recursively, and then merging the two smaller sorted arrays into a single sorted one ALGORITHM Mergesort(..n-1]) //Sorts array A[0..n - 1] by recursive mergesort //Input: An array A[0..n -1] of orderable elements //Output: Array A[0..n - 1] sorted in nondecreasing order ifn >1 copy A[0..In/2] - 1] to B[0.. In/2J-1] copy Alln/2J..n - 1] to C[O.. [n/21-1] Mergesort(B[0.. Ln/2] 1]) Mergesort(C[0..[n/21-1]) Merge(B, C, A) //see below The merging of two sorted arrays can be done as follows. Two pointers (array indices) are initialized to point to the first elements of the arrays being merged The elements pointed to are compared, and the smaller of them is added to a new array being constructed; after that, the index of the smaller element is incremented to point to its immediate successor in the array it was copied from. This operation is repeated until one of the two given arrays is exhausted, and then the remaining elements of the other array are copied to the end of the new array. ALGORITHM Merge(B[0.p 1], C[O..q-1], A[0.p +q -1]) //Merges two sorted arrays into one sorted array //Input: Arrays B[0.p - 1] and C[O..q - 1] both sorted //Output: Sorted array A[0..p +q -1] of the elements of B and C while iStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started