Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a sorted array of n elements, sort a subset n/2 elements in linear time

I have a sorted array of n elements. Now I am given n/2 elements each of which belong to the sorted array. The n/2 elements are taken at random from the sorted array. How to sort these n/2 elements in linear time?

like image 442
user3299864 Avatar asked Feb 12 '14 03:02

user3299864


People also ask

Can sorting be done in linear time?

since you have a range of integers, then yes, it can be linear, but this won't always be the case. This is also known as "bucket sort".

Which sorting technique will you use to sort an already sorted array with only 2 middle numbers unsorted should be efficient?

We can use Insertion Sort to sort the elements efficiently.

Which sorting algorithm can be used to sort in linear time if the numbers are in the range from 1 to n4?

The idea is to use Radix Sort. Following is standard Radix Sort algorithm. Let there be d digits in input integers.


1 Answers

One approach involves hashing. Build a hash set that contains all n / 2 elements drawn from the array. If duplicates are allowed, instead build a hash table from elements to their frequencies. This will take O(n) time, on expectation.

Then, iterate across the sorted array in ascending order and, for each element of the array, check if it's in the hash set / hash table. If so, append that element to the output array (and, if duplicates are allowed, do so once per copy of the element in the set). This will take O(1) time, on expectation, per element of the array, and therefore this step takes time O(n) as well.

Therefore, the total runtime is O(n), on expectation.

Hope this helps!

like image 184
templatetypedef Avatar answered Oct 14 '22 12:10

templatetypedef