C++ Tutorials

C++ Tutorials

Inbuilt Sort in C++ Standard Template Library (STL): Sorting is one of the most basic functions applied to data. This is a built-in function in C++ STL by the name of sort() or std::sort(). it can be increasing or decreasing.

The sort() or std::sort() function in C++ is a built-in function that is used to sort any form of data structure in a particular order. Sort is an in-built function in a C++ STL ( Standard Template Library)

#include<bits/stdc++.h>
#include<iostream>
#include <algorithm>

using namespace std;


int main(){

int n;
cout<<"Enter a number of element array: ";
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
  cout<<"Enter "<<i+1<<" element: ";
  cin>>arr[i];
}
//sort an array using sort() function

sort(arr, arr+n);

for(int i=0; i<n; i++){
  cout<<arr[i]<<", ";
}
return 0 ;
}

Inbuilt Sort in C++ Standard Template Library (STL): Increasing

#include<bits/stdc++.h>
#include<iostream>
#include <algorithm>

using namespace std;
//Define a comparator function
bool compare(int a, int b){
  //incrase
  return a<b;
}

int main(){

int n;
cout<<"Enter a number of element array: ";
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
  cout<<"Enter "<<i+1<<" element: ";
  cin>>arr[i];
}
//sort an array using sort() function
//Compare: sending function as a parameter to another function
sort(arr, arr+n, compare);

for(int i=0; i<n; i++){
  cout<<arr[i]<<", ";
}
return 0 ;
}

Inbuilt Sort in C++ Standard Template Library (STL): Decreasing

#include<bits/stdc++.h>
#include<iostream>
#include <algorithm>

using namespace std;
//Define a comparator function
bool compare(int a, int b){
  //decreasing
  return a>b;
}

int main(){

int n;
cout<<"Enter a number of element array: ";
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
  cout<<"Enter "<<i+1<<" element: ";
  cin>>arr[i];
}
//sort an array using sort() function
//Compare: sending function as a parameter to another function
sort(arr, arr+n, compare);

for(int i=0; i<n; i++){
  cout<<arr[i]<<", ";
}
return 0 ;
}

Inbuilt Sort in C++ Standard Template Library (STL): Comparing function

#include<bits/stdc++.h>
#include<iostream>
#include <algorithm>

using namespace std;
//Define a comparator function
bool compare(int a, int b){
  //comparing function
  cout<<"Comparing "<<a<<" and "<<b<<endl;
  //incrase
  return a<b;
}

int main(){

int n;
cout<<"Enter a number of element array: ";
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
  cout<<"Enter "<<i+1<<" element: ";
  cin>>arr[i];
}
//sort an array using sort() function

sort(arr, arr+n, compare);

for(int i=0; i<n; i++){
  cout<<arr[i]<<", ";
}
return 0 ;
}