0% found this document useful (0 votes)
17 views9 pages

PDF document-41964FCD5818-1

The document discusses the std::sort() function in C++ STL which is used to sort vectors or arrays. It explains how to use sort() to sort in ascending or descending order and how to use a custom comparator to sort in a particular order. The time and space complexity of std::sort() are also provided.

Uploaded by

Nahom Mekonnen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views9 pages

PDF document-41964FCD5818-1

The document discusses the std::sort() function in C++ STL which is used to sort vectors or arrays. It explains how to use sort() to sort in ascending or descending order and how to use a custom comparator to sort in a particular order. The time and space complexity of std::sort() are also provided.

Uploaded by

Nahom Mekonnen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

std::sort() in C++ STL

Difficulty Level : EasyLast Updated : 21 Jan, 2022

We have discussed qsort() in C. C++ STL provides a similar function sort that
sorts a vector or array (items with random access).

It generally takes two parameters, the first one being the point of the
array/vector from where the sorting needs to begin and the second parameter
being the length up to which we want the array/vector to get sorted. The third
parameter is optional and can be used in cases such as if we want to sort the
elements lexicographically.

By default, the sort() function sorts the elements in ascending order.

Below is a simple program to show the working of sort().

CPP
:
// C++ program to demonstrate default behaviour of
// sort() in STL.
#include <bits/stdc++.h>
using namespace std;

int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);

/*Here we take two parameters, the beginning of the


array and the length n upto which we want the array to
be sorted*/
sort(arr, arr + n);

cout << "\nArray after sorting using "


"default sort is : \n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";

return 0;
}

Output :

Array after sorting using default sort is :


0 1 2 3 4 5 6 7 8 9

How to sort in descending order?


sort() takes a third parameter that is used to specify the order in which elements
are to be sorted. We can pass the “greater()” function to sort in descending
order. This function does a comparison in a way that puts greater elements
before.

CPP
:
// C++ program to demonstrate descending order sort using
// greater<>().
#include <bits/stdc++.h>
using namespace std;

int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);

sort(arr, arr + n, greater<int>());

cout << "Array after sorting : \n";


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

return 0;
}

Output:

Array after sorting :


9 8 7 6 5 4 3 2 1 0

How to sort in a particular order?


We can also write our own comparator function and pass it as a third parameter.
This “comparator” function returns a value; convertible to bool, which basically
tells us whether the passed “first” argument should be placed before the passed
“second” argument or not.
For eg: In the code below, suppose intervals {6,8} and {1,9} are passed as
arguments in the “compareInterval” function(comparator function). Now as
i1.first (=6) < i2.first (=1), so our function returns “false”, which tells us that
“first” argument should not be placed before “second” argument and so sorting
will be done in order like {1,9} first and then {6,8} as next.
:
CPP
// A C++ program to demonstrate
// STL sort() using
// our own comparator
#include <bits/stdc++.h>
using namespace std;

// An interval has a start


// time and end time
struct Interval {
int start, end;
};

// Compares two intervals


// according to starting times.
bool compareInterval(Interval i1, Interval i2)
Data
{ Structures Algorithms Interview Preparation Topic-wise Practice C++ Java
return (i1.start < i2.start);
}

int main()
{
Interval arr[]
= { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };
int n = sizeof(arr) / sizeof(arr[0]);

// sort the intervals in increasing order of


// start time
sort(arr, arr + n, compareInterval);

cout << "Intervals sorted by start time : \n";


for (int i = 0; i < n; i++)
cout << "[" << arr[i].start << "," << arr[i].end
<< "] ";

return 0;
}

Output: ▲
:
StartIntervals sorted by start time :
Your[1,9] [2,4] [4,7] [6,8]
Coding Login Register
Journey
The time complexity of std::sort() is:
Now!
1. Best Case – O(N log N)
2. Average Case – O(N log N)
3. Worst Case – O(N log N)

Space Complexity – It may use O( log N) auxiliary space.

?list=PLqM7alHXFySGg6GSRmE2INI4k8fPH5qVB

This article is contributed by Shubham Agrawal. Please write comments if you


find anything incorrect, or you want to share more information about the topic
discussed above
:
Like 374

Previous Next

R ECO M M E N D E D A RT I C L E S Page : 1 2 3 4 5 6

01 fill() and fill_n() functions in C++ STL


31, Mar 16

02 std::transform() in C++ STL (Perform an operation on all elements)


23, Apr 16

03 Count number of unique Triangles using STL | Set 1 (Using set)


23, May 16

04 Permutations of a given string using STL


28, May 16
:
Article Contributed By :

GeeksforGeeks

Vote for difficulty


Current difficulty : Easy

Easy Normal Medium Hard Expert

Improved By : rahuku, AbhishekSharma5, praddyumn, ankitsinghrajput,


varshagumber28, tanmaynikam2002

Article Tags : cpp-algorithm-library, CPP-Library, STL, C Language, C++,


Sorting

Practice Tags : Sorting, STL, CPP

Improve Article Report Issue

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

Load Comments
:
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company
About Us

Careers

Privacy Policy

Contact Us

Copyright Policy

Learn

Algorithms

Data Structures

Machine learning

CS Subjects

Video Tutorials

News

Technology

Work & Career

Business

Finance

Lifestyle
:
Languages
Python

Java

CPP

Golang

C#

Web Development

Web Tutorials

HTML

CSS

JavaScript

Bootstrap

Contribute

Write an Article

Pick Topics to Write

Write Interview Experience

Internships

Video Internship

@geeksforgeeks , Some rights reserved


:

You might also like