Question

1. Implement the merge-sort algorithm a. Determine the correct basic operation 2. Test your algorithm on...

1. Implement the merge-sort algorithm

a. Determine the correct basic operation

2. Test your algorithm on inputs of size 2^10, 2^11 ... 2^20.

If this is too slow then just run it on any set of powers of two.

3. Show the running time of each of these inputs

Choose a basic operation

Count the total number times that this basic operation is done for each

power of 2.

Display this count in a table

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Since you have not mentioned the language of your preference, I am providing the code in JAVA,

CODE

import java.util.Random;

import java.util.Scanner;

public class Main

{

public static void merge(int arr[], int l, int m, int r)

{

int n1 = m - l + 1;

int n2 = r - m;

int L[] = new int [n1];

int R[] = new int [n2];

for (int i=0; i<n1; ++i)

L[i] = arr[l + i];

for (int j=0; j<n2; ++j)

R[j] = arr[m + 1+ j];

int i = 0, j = 0;

int k = l;

while (i < n1 && j < n2)

{

if (L[i] <= R[j])

{

arr[k] = L[i];

i++;

}

else

{

arr[k] = R[j];

j++;

}

k++;

}

while (i < n1)

{

arr[k] = L[i];

i++;

k++;

}

while (j < n2)

{

arr[k] = R[j];

j++;

k++;

}

}

public static void mergeSort(int arr[], int l, int r)

{

if (l < r)

{

int m = (l+r)/2;

mergeSort(arr, l, m);

mergeSort(arr , m+1, r);

merge(arr, l, m, r);

}

}

public static void printArray(int arr[]) {

int n = arr.length;

for (int i=0; i<n; ++i)

System.out.print(arr[i] + " ");

System.out.println();

}

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

for (int k=10; k<=20; k++) {

int n = (int) Math.pow(2, k);

int a[] = new int[n];

int temp[] = new int[n];

Random rand = new Random();

for(int i=0; i<n; i++) {

a[i] = rand.nextInt(100);

}

for(int i=0; i<n; i++) {

temp[i] = a[i];

}

long startTime, endTime, duration;

a = temp;

startTime = System.nanoTime();

mergeSort(a, 0, a.length-1);

endTime = System.nanoTime();

duration = (endTime - startTime) / 1000000;

System.out.println("For n = " + n + ", Merge Sort took " + duration + " milliseconds\n");

}

sc.close();

}

}

Add a comment
Know the answer?
Add Answer to:
1. Implement the merge-sort algorithm a. Determine the correct basic operation 2. Test your algorithm on...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT