# t4ans - CS3230 Tutorial 4 Q3. In merge sort algorithm done...

This preview shows pages 1–2. Sign up to view the full content.

CS3230 Tutorial 4 Q3. In merge sort algorithm done in class, for merging two arrays of size m and n respec- tively, we used one extra array of size m + n . Can you give an algorithm to do the merge which uses an extra array B of size only min( m,n )? Complexity of your algorithm should still be linear in the size of the two arrays. Ans: Below is the main algorithm. Details of why this works was done in the tutorial class. Merge( A,i,k,j ) Assumption: i k < j ; A [ i : k ] and A [ k +1 : j ] are sorted; and k - i j - k - 1 (that is A [ i : k ] is smaller in size than A [ k + 1 : j ]) 1. For r = i to k do { B [ r ] = A [ r ] } 2. p 1 = i ; p 2 = k + 1; p 3 = i 3. While p 1 k , p 2 j do { 3.1 If B [ p 1] A [ p 2], then A [ p 3] = B [ p 1], p 1 = p 1 + 1 Else A [ p 3] = A [ p 2], p 2 = p 2 + 1; Endif 3.2 p 3 = p 3 + 1; } 4. While p 1 k , { A [ p 3] = A [ p 1]; p 1 = p 1 + 1; p 3 = p 3 + 1; } (* Note: we don’t need to do the part While p 2 j { A [ p 3] = A [ p 2];

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 01/06/2012 for the course CS 3230 taught by Professor Sanjay during the Fall '10 term at National University of Singapore.

### Page1 / 2

t4ans - CS3230 Tutorial 4 Q3. In merge sort algorithm done...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online