In: Computer Science
Write a C++ program to find K largest elements in a given array of integers. For eeample, if K is 3, then your program should ouput the largest 3 numbers in teh array. Your program is not supposed to use any additional array.
Code:
#include<iostream>
using namespace std;
int main(){
int n,b,j,m;
cout<<"enter no of elements in
array:"; //reading number of elements
cin>>n;
int a[n],i,max=-1;
for(i=0;i<n;i++){
cout<<"enter
element:";
//reading elements
cin>>a[i];
}
cout<<endl<<"enter number of largest
numbers you want:";
cin>>b;
for(i=0;i<b;i++){
for(j=0;j<n;j++){
if(max<a[j]){
max=a[j];
m=j;
//finding largest element
}
}
cout<<max<<endl;
a[m]=0;
max=-1;
}
}
Output: