Question

Describe an algorithm that selects and sorts k smallest elements from an array A of length...

Describe an algorithm that selects and sorts k smallest elements from an array A of length n of integers. Estimate the running time. The efficiency of your algorithm is important.

Homework Answers

Answer #1

#include <iostream>
using namespace std;

// Swap function to interchange
// the value of variables x and y
int swap(int& x, int& y)
{
   int temp = x;
   x = y;
   y = temp;
}

// Max Heap Class
// arr holds reference to an integer
// array size indicate the number of
// elements in max Heap
class MaxHeap {

   int size;
   int* arr;

public:
   // Constructor to initialize the size and arr
   MaxHeap(int size, int input[]);

   // Min Heapify function, that assumes that
   // 2*i+1 and 2*i+2 are min heap and fix the
   // heap property for i.
   void heapify(int i);

   // Build the min heap, by calling heapify
   // for all non-leaf nodes.
   void buildHeap();
};

// Constructor to initialize data
// members and creating mean heap
MaxHeap::MaxHeap(int size, int input[])
{
   // Initializing arr and size

   this->size = size;
   this->arr = input;

   // Building the Min Heap
   buildHeap();
}

// Min Heapify function, that assumes
// 2*i+1 and 2*i+2 are min heap and
// fix min heap property for i

void MaxHeap::heapify(int i)
{
   // If Leaf Node, Simply return
   if (i >= size / 2)
       return;

   // variable to store the largest element
   // index out of i, 2*i+1 and 2*i+2
   int largest;

   // Index of left node
   int left = 2 * i + 1;

   // Index of right node
   int right = 2 * i + 2;

   // Select minimum from left node and
   // current node i, and store the minimum
   // index in smallest variable
   largest = arr[left] > arr[i] ? left : i;

   // If right child exist, compare and
   // update the smallest variable
   if (right < size)
       largest = arr[right] > arr[largest]
                           ? right : largest;

   // If Node i violates the min heap
   // property, swap current node i with
   // smallest to fix the min-heap property
   // and recursively call heapify for node smallest.
   if (largest != i) {
       swap(arr[i], arr[largest]);
       heapify(largest);
   }
}

// Build Max Heap
void MaxHeap::buildHeap()
{
   // Calling Heapify for all non leaf nodes
   for (int i = size / 2 - 1; i >= 0; i--) {
       heapify(i);
   }
}

void FirstKelements(int arr[],int size,int k){
   // Creating max Heap for given
   // array with only k elements
   MaxHeap* m = new MaxHeap(k, arr);

   // Loop For each element in array
   // after the kth element
   for (int i = k; i < size; i++) {

       // if current element is smaller
       // than minimum element, do nothing
       // and continue to next element
       if (arr[0] < arr[i])
           continue;

       // Otherwise Change minimum element to
       // current element, and call heapify to
       // restore the heap property
       else {
           arr[0] = arr[i];
           m->heapify(0);
       }
   }
   // Now min heap contains k maximum
   // elements, Iterate and print
   for (int i = 0; i < k; i++) {
       cout << arr[i] << " ";
   }
}
// Driver Program
int main()
{

   int arr[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };

   int size = sizeof(arr) / sizeof(arr[0]);

   // Size of Min Heap
   int k = 3;

   FirstKelements(arr,size,k);

   return 0;
}

Use Max Heap.

1) Build a Max Heap MH of the first k elements (arr[0] to arr[k-1]) of the given array. O(k)

2) For each element, after the kth element (arr[k] to arr[n-1]), compare it with the root of MH.
……a) If the element is greater than the root then make it root and call heapify for MH
……b) Else ignore it.
// The step 2 is O((n-k)*logk)

3) Finally, MH has k largest elements and root of the MH is the kth largest element.

Time Complexity: O(k + (n-k)Logk) without sorted output. If sorted output is needed then O(k + (n-k)Logk + kLogk)

Know the answer?
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
Similar Questions
A is an array with n elements such that each element is at most in k...
A is an array with n elements such that each element is at most in k position away of its ordered position. Give an algorithm that sorts the elements of A on O(n log k). Example: [2,1,4,3]
Let mixsort(A, 1, n) be an algorithm that sorts an array A with n integers. It...
Let mixsort(A, 1, n) be an algorithm that sorts an array A with n integers. It works as follows: mixsort(A, p, q){ if p ≥ q, return; r=partition(A, p, q); //run mixsort on the low part mixsort(A, p, r − 1); //run insert sort on the high part insertsort(A, r + 1, q); } Compute the best-case, worst-case, and average-case complexities of mixsort.
Java : Modify the selection sort algorithm to sort an array of integers in descending order....
Java : Modify the selection sort algorithm to sort an array of integers in descending order. describe how the skills you have gained could be applied in the field. Please don't use an already answered solution from chegg. I've unfortunately had that happen at many occasion ....... ........ sec01/SelectionSortDemo.java import java.util.Arrays; /** This program demonstrates the selection sort algorithm by sorting an array that is filled with random numbers. */ public class SelectionSortDemo { public static void main(String[] args) {...
2. Design a deterministic algorithm to solve the following problem. input: An array A[1...n] of n...
2. Design a deterministic algorithm to solve the following problem. input: An array A[1...n] of n integers. output: Two different indices i and j such that A[i] = A[j], if such indices exist. Otherwise, return NONE. Your algorithm must take O(n log(n)) time. You must describe your algorithm in plain English (no pseudocode) and you must explain why the running time of your algorithm is O(n log(n)).
1. Given an n-element array A, Algorithm X executes an O(n)-time computation for each even number...
1. Given an n-element array A, Algorithm X executes an O(n)-time computation for each even number in A and an O(log n)-time computation for each odd number in A. What is the best-case running time of Algorithm X? What is the worst-case running time of Algorithm X? 2. Given an array, A, of n integers, give an O(n)-time algorithm that finds the longest subarray of A such that all the numbers in that subarray are in sorted order. Your algorithm...
3. (10 marks) Describe a recursive algorithm for finding the maximum element in a array A...
3. Describe a recursive algorithm for finding the maximum element in a array A of n elements. Analyze its time complexity using a recursion tree.
Write an application in Java which includes an algorithm that takes an array of any size,...
Write an application in Java which includes an algorithm that takes an array of any size, selects the high and low integer from the array of integers with each pass and builds a new array of integers by inserting the high and low selection with each pass. Your output should show the original array of integers and the output of each pass on a new line. Note: You can assume all integers are positive, but your code must work for...
Let us consider Boruvka/Sollin's algorithm as shown . Note that Boruvka/Sollin algorithm selects several edges for...
Let us consider Boruvka/Sollin's algorithm as shown . Note that Boruvka/Sollin algorithm selects several edges for inclusion in T at each stage. It terminates when only one tree at the end of a stage or no edges to be selected. One Step of Boruvka/Sollin's Algorithm 1: Find minimum cost edge incident to every vertex. 2: Add to tree T. 3: Remove cycle if any. 4: Compress and clean graph (eliminate multiple edges). (a) Suppose that we run k phases of...
Given an array, A, of n−2 unique integers in the range from 1 to n, describe...
Given an array, A, of n−2 unique integers in the range from 1 to n, describe an O(n)-time method for finding the two integers in the range from 1 to n that are not in A. You may use only O(1) space in addition to the space used by A.
In this programming exercise you will create an algorithm for solving the following version of the...
In this programming exercise you will create an algorithm for solving the following version of the m Smallest Numbers problem.   Instead of just returning the m smallest values as in homework 1, you want to return a list of the positions where the m smallest values are located without changing the original array. Your algorithm should meet the following specifications: mSmallest( L[1..n], m ) Pre: L is a list of distinct integer values. n is the number of elements in...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT