Finding the median of an unsorted array

后端 未结 8 1030
后悔当初
后悔当初 2020-11-28 05:01

To find the median of an unsorted array, we can make a min-heap in O(nlogn) time for n elements, and then we can extract one by one n/2 elements to get the median. But this

相关标签:
8条回答
  • 2020-11-28 05:51

    Let the problem be: finding the Kth largest element in an unsorted array.

    Divide the array into n/5 groups where each group consisting of 5 elements.

    Now a1,a2,a3....a(n/5) represent the medians of each group.

    x = Median of the elements a1,a2,.....a(n/5).

    Now if k<n/2 then we can remove the largets, 2nd largest and 3rd largest element of the groups whose median is greater than the x. We can now call the function again with 7n/10 elements and finding the kth largest value.

    else if k>n/2 then we can remove the smallest ,2nd smallest and 3rd smallest element of the group whose median is smaller than the x. We can now call the function of again with 7n/10 elements and finding the (k-3n/10)th largest value.

    Time Complexity Analysis: T(n) time complexity to find the kth largest in an array of size n.

    T(n) = T(n/5) + T(7n/10) + O(n)

    if you solve this you will find out that T(n) is actually O(n)

    n/5 + 7n/10 = 9n/10 < n

    0 讨论(0)
  • 2020-11-28 05:58

    Quickselect works in O(n), this is also used in the partition step of Quicksort.

    0 讨论(0)
提交回复
热议问题