1
file:///J|/E%20books/Dropbox/ebook/cc/Algo%20n%20puzzles/Algo/Array/Merge%202%20sorted%20arrays%20inplace/Question.txt Q1) Given an integer array of which both first half and second half are sorted. Write a function to merge the two parts to create one single sorted array in place [do not use any extra space]. e.g. If input array is [1,3,6,8,-5,-2,3,8] It should be converted to: [-5,-2,1,3,3,6,8,8] //Use Quicksort or Heapsort Note we cant have O(n) solution as if that was possible than the merge procedure of MergeSort could have been done inplace. Q2) if the 2 sorted arrays are not stored in contiguous location ie.arrays 'a' and 'b' are sorted and stored in different memory location and we need to merge them in place. //Sol 1. Make a MAXHEAP of both the arrays. 2. Now compare the root elements of both the heaps. Swap the max element of the two with b[HEAPSIZE] i.e last element of the second heap. Call MAXHEAPIFY on the root node of the array from which the max element has come. 3.Thus continusing in this way everytime we store the max of the 2 heaps at b[heapsize] and reduce the size of array b. 4. Finally the array b will exhaust and we will be lefe with array 'a' which can be sorted in O(n logn) using HEAPSORT. file:///J|/E%20books/Dropbox/ebook/cc/Algo%20n%20puzzles/Algo/Array/Merge%202%20sorted%20arrays%20inplace/Question.txt [3/24/2012 10:28:39 AM]

Inplace Merge of Two Sorted Array

Embed Size (px)

Citation preview

Page 1: Inplace Merge of Two Sorted Array

file:///J|/E%20books/Dropbox/ebook/cc/Algo%20n%20puzzles/Algo/Array/Merge%202%20sorted%20arrays%20inplace/Question.txt

Q1) Given an integer array of which both first half and second half are sorted. Write a function to merge the two parts to create one single sorted array in place [do not use any extra space].e.g. If input array is [1,3,6,8,-5,-2,3,8] It should be converted to: [-5,-2,1,3,3,6,8,8]

//Use Quicksort or HeapsortNote we cant have O(n) solution as if that was possible than the merge procedure of MergeSort could have been done inplace.

Q2) if the 2 sorted arrays are not stored in contiguous location ie.arrays 'a' and 'b' are sorted and stored in different memory location and we need to merge them in place.

//Sol1. Make a MAXHEAP of both the arrays.2. Now compare the root elements of both the heaps. Swap the max element of the two with b[HEAPSIZE] i.e last element of the second heap. Call MAXHEAPIFY on the root node of the array from which the max element has come.3.Thus continusing in this way everytime we store the max of the 2 heaps at b[heapsize] and reduce the size of array b.4. Finally the array b will exhaust and we will be lefe with array 'a' which can be sorted in O(n logn) using HEAPSORT.

file:///J|/E%20books/Dropbox/ebook/cc/Algo%20n%20puzzles/Algo/Array/Merge%202%20sorted%20arrays%20inplace/Question.txt [3/24/2012 10:28:39 AM]