Professional Documents
Culture Documents
Experiment Title:: K Largest Element in Array
Experiment Title:: K Largest Element in Array
Experiment Title:: K Largest Element in Array
2. Task to be done:
WAP in C++ to find the Kth largest element in an array using template and C++STL.
ALGORITHM_bubble(array A, int K )
1. n = length of A
2. For i = 0 to K {
For j = 0 to n-i-1 {
if( A[j] > A[j+1] ){
SWAP A[j] and A[j+1]
}}}
3. Return (n-K+1)th element
4. Steps for experiment/practical:
CODE:
#include<iostream>
#include<bits/stdc++.h>
void sortArray(){
sort(this->arr.begin(), this->arr.end(), greater<T>());
}
void displayArray(){
cout<<"\n\n Array : \t";
for(auto i=arr.begin(); i!=arr.end(); i++)
cout<< *i << " , " ;
}
// SOLUTION by Method 1
T kth_largest_approach_one(int k){
// modified bubble sort
T temp;
int n = this->arr.size();
return this->arr[this->arr.size()-k];
}
// __ SOLUTION __
T kth_largest_approach(int k){
// sort method
sort(this->arr.begin(), this->arr.end(), greater<T>());
return this->arr[k-1];
}
};
int main(){
vector<int> vecInt = { 1, 120, 90, 100, -14, 200, 119, 14, 3, 2, -2, 9 };
vector<double> vecDouble = { 0.46395, 0.22783,
0.71528, 0.08110,
0.51652, 0.51169,
0.10889, 0.15417,
0.94130, 0.38098
};
vector<string> vecString = { "the", "north", "eye", "is", "an", "under", "construction",
"residential", "skyscraper", "in", "noida" };
MyArray<int> obj(vecInt);
MyArray<double> obj2(vecDouble);
MyArray<string> obj3(vecString);
obj.displayArray();
cout<<"\n 6th Largest : \t"<<obj.kth_largest_approach_one(6);
obj2.displayArray();
cout<<"\n 5th Largest : \t"<<obj2.kth_largest_approach(5);
obj3.displayArray();
cout<<"\n 7th Largest : \t"<<obj3.kth_largest_approach_one(7);
obj.sortArray();
obj3.sortArray();
obj.displayArray();
obj2.displayArray();
obj3.displayArray();
return 0;
}
7. Result/Output/Writing Summary:
Conclusion/ Remarks:
1. Templates are very crucial for generic programming which is very convenient in
coding.
2. Templates are excellent to reduce the boilerplate code and make it easier to organize
multiple data types.
4. STL proves absolutely crucial when time is short, as it saves the programmer from
having to rewrite every single implementation, even the basic ones, thus saving
time.
5. STL also plays an important role by reducing the customized implementation w.r.t.
Standard implementations, thus making coding less prone to errors and at the same
time making the code such that spotting errors / debugging becomes an easier task.