Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

FIGURED THE ANSWER OUT! NO NEED TO ANSWER UNLESS YOU WANT TO! Write a program to

ID: 3854292 • Letter: F

Question

FIGURED THE ANSWER OUT! NO NEED TO ANSWER UNLESS YOU WANT TO!

Write a program to find the k largest elements of a file. Allocate an array of size k and while you read the numbers from the file, store the k largest numbers in the array. When you read the next element from the file, find if the array needs to be modified or not. Consider the below figure as an example. Assume that next element read is 80. Since 80 is larger than the smallest element, we need to shift elements assign4 a.txt 5 996 980 956 932 929

Explanation / Answer

#include <bits/stdc++.h>
using namespace std;


int main(int argc, char const *argv[])
{
  

   const char* name=argv[1];
   ifstream filen(name);
int k=atoi(argv[2]);
int * arr=new int[k];
int i=0;
//read first k elements in array
   while(i<k&&filen>>arr[i])
   {
       i++;
   }

   int min=arr[0];
//find minimum element in arr
   for (int i = 0; i < k; ++i)
   {
       if(min>arr[i])
           min=arr[i];
   }
int e;
   while(filen>>e)
   {
       if(e>min)//if next element read from file is greater than min then replace min

       {
           for (int i = 0; i < k; ++i)
           {
               if(min==arr[i])
               {
                   arr[i]=e;
                   break;
               }
           }
           //change min in arr and find new min
           min=arr[0];
           for (int j = 0; j < k; ++j)
               {
                   if(min>arr[j])
                       min=arr[j];
               }

       }
      
   }

   sort(arr,arr+k, std::greater<int>());//sort descending order

//print kth largest elements
   for (int i = 0; i <k; ++i)
   {
       cout<<arr[i]<<" ";
   }
   return 0;
}

====================================================================

Output:

akshay@akshay-Inspiron-3537:~/Chegg$ g++ kthlargest.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out input.txt 5
97 83 80 76 65

==============================================================

Let me know if you have any problem