Sorting an array using C++ inbuilt function

In this tutorial, we will learn how to use C++ inbuilt function to sort a particular array. C++ inbuilt sort function is very fast and it takes O(n*logn) to sort an array which uses inbuilt merge sort or quick sort which is much better than bubble sort, insertion sort, etc.in terms of time complexity.

Let us take an array –>arr[n].

  • Sort function will look like that:   sort(arr, arr+n)

It means that we are sorting the array from start to end. We can sort an array from any index to any index using this function. If nothing is defined then it will sort array in increasing order.

Let us first know how to sort it in increasing order then we will sort it in decreasing order.

Program to sort array in increasing order using C++ inbuilt function

Cpp source code:

// Program to sort array in increasing order using C++ inbuilt function 
#include<bits/stdc++.h>
using namespace std;
int main()
{
  int n;
  cout<<"Enter number of elements you want to take in array: ";
  cin>>n;
  cout<<"\nEnter array elements:\n";
  int arr[n];
  for(int i=0;i<n;i++)
  {
    cin>>arr[i];
  }

  // Inbuit Sort function
  sort(arr,arr+n);
  cout<<"\nArray after sorting in increasing order:\n";
  for(int i=0;i<n;i++)
  {
    cout<<arr[i]<<" ";
  }
  return 0;
}

Input/Output:

Enter number of elements you want to take in array: 5

Enter array elements:
5 4 3 2 1

Array after sorting in increasing order:
1 2 3 4 5

Now let us have a look at how we will sort it in decreasing order. We will have to make a function to compare elements so that we can get it sorted in decreasing order.

We will have to declare sort function as follows: sort(arr, arr+n, compare). Here compare is a function, let’s see it in our code how to declare this function.

Program to sort array in decreasing order

Cpp source code:

// Program to sort array in decreasing order using C++ inbuilt function
#include<bits/stdc++.h>
using namespace std;

// Declaring compare function
bool compare(int a,int b)
{
  return a>b;
}
int main()
{
  int n;
  cout<<"Enter number of elements you want to take in array: ";
  cin>>n;
  cout<<"\nEnter array elements:\n";
  int arr[n];
  for(int i=0;i<n;i++)
  {
    cin>>arr[i];
  }
  
  // inbuilt sort function
  sort(arr,arr+n,compare);
  cout<<"\nArray aftr sorting in decreasing order:\n";
  for(int i=0;i<n;i++)
  {
    cout<<arr[i]<<" ";
  }
  return 0;
}

Input/Output:

Enter number of elements you want to take in array: 5

Enter array elements:
1 2 3 4 5

Array aftr sorting in decreasing order:
5 4 3 2 1

You may also learn:

How to implement Topological Sorting in Python

How the Bubble Sorting technique is implemented in Python

Do not forget to comment if you find anything wrong in the post or you want to share some information regarding the same.

Leave a Reply

Your email address will not be published. Required fields are marked *