Simple sorting
Lesson 12 of 26 in Coddy's Arrays in C++ course.
When an array is sorted it is easier to answer many questions such as which is the biggest or smallest element etc. The basic technique of sorting an array is by having two iterators.
1. we create a nested loop inside a for loop and compare the ith element with all the elements ahead of it.
for(int i=0;i<m;i++){
for(int j=i+1;j<n;j++){
//compare the elements
}
}2. if the ith element is greater than the jth one then swap these two.
for(int i=0;i<m;i++){
for(int j=i+1;j<n;j++){
if(arr[i]>arr[j]){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}The array will get sorted.
Challenge
Given an unsorted array and its lengh n, print the 2nd largest and 2nd smallest element respectively separated by space.
Try it yourself
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
//Code here
return 0;
}