Question

Suppose that you are given an array of N elements. Develop an optimum algorithm that finds...

Suppose that you are given an array of N elements. Develop an optimum algorithm that finds the minimum k elements of this array in at most nlogn time. Try your algorithm on an example N-sized array and some value of k.

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

Below is the implementation in C++.

CODE

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

// Function to find the K'th smallest element in the
// array using max-heap
int findKthSmallest(vector<int> const &v, int k)
{
   // create an max-heap using std::priority_queue and
   // insert first k elements of the array into the heap
   priority_queue<int, vector<int>> pq(v.begin(), v.begin() + k);

   // do for remaining array elements
   for (int i = k; i < v.size(); i++)
   {
       // if current element is less than the root of the heap
       if (v[i] < pq.top())
       {
           // replace root with the current element
           pq.pop();
           pq.push(v[i]);
       }
   }

   // return the root of max-heap
   return pq.top();
}

// Find K'th smallest element in an array
int main()
{
   vector<int> vec = { 7, 4, 6, 3, 9, 1 };
   const size_t k = 3;

   cout << "K'th smallest element in the array is " <<
           findKthSmallest(vec, k);

   return 0;
}

Add a comment
Know the answer?
Add Answer to:
Suppose that you are given an array of N elements. Develop an optimum algorithm that finds...
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