1. Analyze the running time of insertion sort on an array of size n. Show detailed analysis of the steps and express the final answer using order notation. Assume all basic operations take unit time (c = 1). void insertionSort(int[] arr) { // Sort arr[0..arr.length-1]. for(int i=1; i<arr.length; i++) { int key = arr[i]; int j = i-1; // Insert key into the right spot while (j >= 0 && arr[j] > key) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = key; } }
Added by Tracie S.
Close
Step 1
The outer loop runs from i=1 to i=n-1. This loop iterates n-1 times. Show more…
Show all steps
Your feedback will help us improve your experience
Supreeta N and 74 other AP CS educators are ready to help you.
Ask a new question
Labs
Want to see this concept in action?
Explore this concept interactively to see how it behaves as you change inputs.
Key Concepts
Recommended Videos
Processing time of InsertionSort is c · n^2. To merge k pre-sorted subarrays that contain together n items, you have to compare the k top items in all the sub-arrays to choose the current maximum item and place it into the sorted array (assuming that all the items have to be sorted in ascending order). Therefore, the time for merging is proportional to (k - 1) · n. Let the processing time of the merge be c · (k - 1) · n where the scale factor has the same value as for InsertionSort. Analyze whether it is possible to accelerate sorting of n items in the following way: - Split the initial array of size n into k subarrays of size n/k. The last subarray may be longer to preserve the total number of items n, but do not go into such details in your analysis. - Sort each subarray separately by InsertionSort. - Merge the sorted subarrays into a final sorted array. If you have found that the acceleration is possible, then find the optimum value of k and compare the resulting time complexity of this sorting algorithm to that of InsertionSort and MergeSort.
Aarya B.
Suppose we have an O(n) time algorithm that finds the median of an unsorted array. Now consider a QuickSort implementation where we first find the median using the above algorithm, then use the median as the pivot. What will be the worst-case time complexity of this modified QuickSort? Which one is faster for a data set of 1000 elements to be sorted? A) O(n^2 Logn) B) O(n^2) C) O(n Logn Logn) D) O(nLogn)
Adi S.
How many comparisons does the insertion sort use to sort the list $1,2, \ldots, n ?$
Algorithms
Recommended Textbooks
Computer Science and Information Technology
Introduction to Programming Using Python
Computer Science - An Overview
Transcript
Watch the video solution with this free unlock.
EMAIL
PASSWORD