STL-02 Sort in C++ Standard Template Library

Sort in C++ Standard Template Library (STL)

Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a built-in function in C++ STL by the name of sort().
This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort .By default, it uses QuickSort but if QuickSort is doing unfair partitioning and taking more than N*logN time, it switches to HeapSort and when the array size becomes really small, it switches to InsertionSort.

The prototype for sort is :

sort(startAddress, endAddress)

startaddress: the address of the first element of the array
endaddress: the address of the next contiguous location of 
            the last element of the array.
So actually sort() sorts in the range of [startAddress,endAddress)

An Example for sort

// C++ progrma to sort an array
#include <algorithm>
#include <iostream>

using namespace std;

void show(int a[], int array_size) {
   for (int i = 0; i < array_size; ++i)
   	cout << a[i] << " ";
}

// Driver code
int main() {
   int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };

   // size of the array
   int asize = sizeof(a) / sizeof(a[0]);
   cout << "The array before sorting is : \n";

   // print the array
   show(a, asize);

   // sort the array
   sort(a, a + asize);

   cout << "\n\nThe array after sorting is :\n";

   // print the array after sorting
   show(a, asize);

   return 0;
}

Output

The array before sorting is : 
1 5 8 9 6 7 3 4 2 0 

The array after sorting is :
0 1 2 3 4 5 6 7 8 9 

More details on std::sort() in C++ STL

sort 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, sort() function sorts the element in ascending order.

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

// 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 

<bits/stdc++.h> is basically a header file that includes every standard library.

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 greater() function to sort in descending order. This function does a comparison in a way that puts greater element before.

// 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 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 example: 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.

// 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 staring times. 
bool compareInterval(Interval i1, Interval i2) { 
	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:

Intervals sorted by start time : 
[1,9] [2,4] [4,7] [6,8] 

More about c++ STL, turn to this page.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值