In: Computer Science
Write a function that takes a list of integers as input and returns a list with only the even numbers in descending order (Largest to smallest)
Example: Input list: [1,6,3,8,2,5] List returned: [8, 6, 2]
Do not use any special or built in functions like append, reverse etc.
#include <bits/stdc++.h>
using namespace std;
void bubbleSort(vector<int> &arr){
int n = arr.size();
for(int i=0;i<n;i++){ // loop for the bubble sort
for(int j=0;j<n-i-1;j++){
if(arr[j]<arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return;
}
vector<int> solve(int n, vector<int> &v){
vector<int> res; // forming the result list which is going to be returned
for(int i=0;i<n;i++){ // iterating on all the elements of given list of elements
if(v[i]%2 ==0){ // checking the condition for even elements
res.push_back(v[i]);
}
}
bubbleSort(res); // calling the bubble sort function to sort in descending order
return res; // returning the list of even elements arranged in descending order
}
int main() {
int n; // n is the variable
cin>>n; // taking input - no of elements present in the list
vector<int> v(n); // forming the list of n elements
for(int i=0;i<n;i++) cin>>v[i]; // taking input - the elements present in the list
vector<int> res = solve(n,v); // calling the required function solve - to seperate the even elements
for(int i=0;i<res.size();i++) cout<<res[i]<<" "; // printing the resulted list
cout<<endl;
}