Tweaking sort() function C++

C++ comes with inbuilt sort() function in the ‘algorithm.h’ module which can be really handy to both beginner as well as experienced programmers.In this post,we’ll try to explore sort() function and extend it’s functionality by altering the comparison function in the sorting algorithm.

Lets get started!

Syntax – sort(first,last,comp)

  • Here,’first’ and ‘last’ refers to the pointer to the first and last element.
  • ‘comp’ is the name of the function that accepts two values,compares them and then returns a boolean value.it is absolutely optional.
  • In the absence of ‘comp’ , an operator overloaded ‘<‘ function name is used.

So,lets discuss two techniques to use sort function.

//============================================================================
// Name        : sort_func.cpp
// Author      : Prateek Agarwal
// Institution : NIT Jalandhar
//============================================================================

#include <bits/stdc++.h>
using namespace std;

struct node{
	int val;
};

node a[5];

//this function only accepts struct/class type arguments.

bool operator <(node x,node y){
	//if x.val is less than y.val return true else false
	return x.val<y.val;
}

int main(){
	a[0].val = 2;
	a[1].val = 1;
	a[2].val = 4;
	a[3].val = 3;
	a[4].val = 5;

	sort(a,a+5);
	for(int i=0;i<5;i++) cout << a[i].val << " ";

	return 0;
}

 

Output – 1 2 3 4 5

Another technique is by providing a name to the function.We’ll take the name ‘func’.

//============================================================================
// Name        : sort_func.cpp
// Author      : Prateek Agarwal
// Institution : NIT Jalandhar
//============================================================================

#include <bits/stdc++.h>
using namespace std;

vector<int> a;

bool func(int x,int y){
	return x<y;
}

int main(){
	a.push_back(2);
	a.push_back(1);
	a.push_back(4);
	a.push_back(3);
	a.push_back(5);

	sort(a.begin(),a.end(),func);

	for(int i=0;i<5;i++) cout << a[i] << " ";

	return 0;
}

 

Output – 1 2 3 4 5

Since you are using a custom function , you may pass arguments of any but same type.Also this time it is mandatory to pass the function name as the third argument.

Note,here the function is able to accept ‘int’ values(since we are using a custom function name).If we use the operator overloaded function(first technique) , then we are bound to use struct/class only.

Now , lets see how the sort() function behaves if we alter the comparison function.

Lets begin by changing the direction of the comparison operator.

//============================================================================
// Name        : sort_func.cpp
// Author      : Prateek Agarwal
// Institution : NIT Jalandhar
//============================================================================

#include <bits/stdc++.h>
using namespace std;


bool comp(int x,int y){
	return x>y;	//returns true if x>y(reversed the order)
}

int main(){
	int x[] = {2,1,4,3,5};
	vector<int> a(x,x+5);
	sort(a.begin(),a.end(),comp);
	for(int i=0;i<5;i++) cout << a[i] << " ";
	return 0;
}

//OUTPUT - 5 4 3 2 1

 

This time we’ve got the result printed in non-increasing format.

And here’s how you can sort strings .

//============================================================================
// Name        : sort_func.cpp
// Author      : Prateek Agarwal
// Institution : NIT Jalandhar
//============================================================================

#include <bits/stdc++.h>
using namespace std;

struct node{
	char s[10];
};

node a[5];

bool operator <(node x,node y){
	if (strcmp(x.s,y.s)<0) return true;
	else return false;
}

int main(){
	strcpy(a[0].s,"aaca");
	strcpy(a[1].s,"aca");
	strcpy(a[2].s,"aaaa");
	strcpy(a[3].s,"zadd");
	strcpy(a[4].s,"baca");
	sort(a,a+5);
	for(int i=0;i<5;i++) cout << a[i].s << " ";
	return 0;
}

//OUTPUT - aaaa aaca aca baca zadd

 

Now suppose, You have to sort various cartesian co-ordinates given such that smaller x co-ordinate should appear before larger x co-ordinate.If two co-ordinates have same value of x , then sort according to y.

Here’s the code –

//============================================================================
// Name        : sort_func.cpp
// Author      : Prateek Agarwal
// Institution : NIT Jalandhar
//============================================================================

#include <bits/stdc++.h>
using namespace std;

struct node{
	int x,y;
};

node c[5];

bool operator <(node a,node b){
	if (a.x==b.x) return a.y<b.y;
	else return a.x<b.x;
}

int main(){
	c[0].x = 1; c[0].y = 2;
	c[1].x = 1; c[1].y = 4;
	c[2].x = 3; c[2].y = 7;
	c[3].x = 1; c[3].y = 1;
	c[4].x = 2; c[4].y = 7;
	sort(c,c+5);
	for(int i=0;i<5;i++) cout << "(" << c[i].x << "," << c[i].y << ")" << " ";
	return 0;
}

//INPUT  - (1,2) (1,4) (3,7) (1,1) (2,7)
//OUTPUT - (1,1) (1,2) (1,4) (2,7) (3,7)

 

Depending upon different situations, modifying the comparison function can help in making your code compact as well as speeding up your programming.

Feel free to drop a comment below 🙂

 

2 thoughts on “Tweaking sort() function C++

Leave a comment