# sorted function using compare function

• Last Update :
• Techknowledgy :

When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.,The compare function should return a negative, zero, or positive value, depending on the arguments:,The purpose of the compare function is to define an alternative sort order.,The function calculates 40 - 100 (a - b), and since the result is negative (-60),  the sort function will sort 40 as a value lower than 100.

`const fruits = ["Banana", "Orange", "Apple", "Kiwi"];;`

Suggestion : 2

Lets walk through a simple example... Suppose you're only sorting some numbers, so we have a very simple compare function:

```function compare(a, b) {
return a - b;
}```

Now lets suppose this is our list of numbers to sort:

`var numbers = [1, 5, 3.14];`

When you call `numbers.sort(compare)`, internally it will actually execute:

```compare(1, 5); // Returns -4, a is less than b
compare(1, 3.14); // Return -2.14, a is less than b
compare(5, 3.14); // returns 1.86, a is greater than b```

Your function could have an `if / else if / else` structure to decide what result to return, but for numbers simply returning (a-b) will achieve this for you because the result of the subtraction will be -ve, 0 or +ve and correctly put the numbers in ascending order. Returning (b-a) would put them descending:

```  var sortedArray = myArray.sort(function(a, b) {
return (a - b);
});```

If you had an array of objects and wanted to sort on some particular property or properties of the objects you could do that too. Assuming, e.g., objects in this format:

```{
id: 1,
name: "Fred",
phone: "0262626262"
}```

Then you could sort an array of such objects by their 'id' attribute as follows:

```var sortedArray = myArray.sort(function(a, b) {
return (a.id - b.id);
});```

ex1 :strings

```var animals = ["Horse", "Cat", "Tiger", "Lion"];
animals.sort();```

ex2 : numbers

```var marks = [70, 90, 60, 80];
marks.sort(function(a, b) {
return a > b
}); //ascending , a < b descending . ```

second parameter is b.

```function compare(a, b) {
//  make some operations to calculate these variables as true or false
//     weNeedToMoveFirstParameterInPositiveDirection
//     weDoNotNeedToMove
//     weNeedToMoveFirstParameterInNegativeDirection

// just think about numerical axis <------(-1)---(0)---(1)------>
if (weNeedToMoveFirstParameterInPositiveDirection) return 1;
if (weDoNotNeedToMove) return 0;
if (weNeedToMoveFirstParameterInNegativeDirection) return -1;
}```

Suggestion : 3

I have seen compare function in sort to sort using the second element and all! But i am not understanding the syntax. Can anyone please provide the syntax to sort the pairs by the sum of the elements or product of the elements so that i will get the idea of the compare function,Suppose if i can use only qsort() where should i give compare as the argument in the function call? If C++ is blocked in a contest with only C/JAVA,Well the general syntax of the sort() function is sort(start,end,overload function); where the “overload function” is the one we provide to overload the original function of the c++. As for sorting by sum or product just write a overload function as:,Please refer this link: http://www.cplusplus.com/reference/cstdlib/qsort/

Well the general syntax of the sort() function is
where the “overload function” is the one we provide to overload the original function of the c++.
As for sorting by sum or product just write a overload function as:

```typedef pair<int,int> ii;
#define first f
#define s second
bool cmp(ii a,ii b)
{
int as=a.f+a.s,bs=b.f+b.s;
if(as!=bs)
return as<bs;
return a.f<b.f;
}```

struct _pair
{
int first, second;
};

```    /*in order to sort an array of _pair in increasing order based on the sum/product of the elements of _pair write a compare function like this.. The value returned (either 1 or 0) indicates whether the element passed as first argument is considered to go before the second.... */

int compare(const _pair & x,
const _pair & y) {
return (x.first + x.second) < (y.first + y.second); //modify it for sorting by product of elements
}```

Suggestion : 4

Last Updated : 06 Jul, 2022

```Array after sorting using
default sort is:
0 1 2 3 4 5 6 7 8 9```

```Array after sorting:
9 8 7 6 5 4 3 2 1 0```

```Array after sorting:
0 1 2 3 4 5 6 7 8 9```

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

```The array before sorting is: 1 5 8 9 6 7 3 4 2 0
The array after sorting is(asc): 0 1 2 3 4 5 6 7 8 9
The array after sorting is(desc): 9 8 7 6 5 4 3 2 1 0
The array after sorting is(asc but our comparator class): 0 1 2 3 4 5 6 7 8 9
The array after sorting is(asc but our comparator
function): 0 1 2 3 4 5 6 7 8 9```

Suggestion : 5

```// Functionless
sort()

// Arrow function
sort((a, b) => {
/* … */ })

// Compare function
sort(compareFn)

// Inline compare function
sort(function compareFn(a, b) {
/* … */ })```
```function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}```
```function compareNumbers(a, b) {
return a - b;
}```
```const numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]

// OR

const numbers2 = [4, 2, 5, 1, 3];
numbers2.sort((a, b) => a - b);
console.log(numbers2);
// [1, 2, 3, 4, 5]```
```const items = [{
name: 'Edward',
value: 21
},
{
name: 'Sharpe',
value: 37
},
{
name: 'And',
value: 45
},
{
name: 'The',
value: -12
},
{
name: 'Magnetic',
value: 13
},
{
name: 'Zeros',
value: 37
}
];

// sort by value
items.sort((a, b) => a.value - b.value);

// sort by name
items.sort((a, b) => {
const nameA = a.name.toUpperCase(); // ignore upper and lowercase
const nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}

// names must be equal
return 0;
});```
```const stringArray = ['Blue', 'Humpback', 'Beluga'];
const numberArray = [40, 1, 5, 200];
const numericStringArray = ['80', '9', '700'];
const mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];

function compareNumbers(a, b) {
return a - b;
}

stringArray.join(); // 'Blue,Humpback,Beluga'
stringArray.sort(); // ['Beluga', 'Blue', 'Humpback']

numberArray.join(); // '40,1,5,200'
numberArray.sort(); // [1, 200, 40, 5]
numberArray.sort(compareNumbers); // [1, 5, 40, 200]

numericStringArray.join(); // '80,9,700'
numericStringArray.sort(); // ['700', '80', '9']
numericStringArray.sort(compareNumbers); // ['9', '80', '700']

mixedNumericArray.join(); // '80,9,700,40,1,5,200'
mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']
mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']```

Suggestion : 6

The compare function checks if you want to return first number before second number. Return true if yes and false if no. Simple!,Your comparefn isn't a compare function since it does not fulfil the requirements of the Compare concept, namely that of transitivity. Thus sort can not work with it.,You should use first_value < second_value instead of first_value <= second_value in your compare function.,Please explain me a dry run of this test case with the custom compare function which I have made. It would be of great help. Thanks in Advance!

Hello Codeforces! In the contest, Codeforces Round #648, in B problem- Trouble Sort, I thought of using the Custom Compare Function, though later I realized it wasn't required here. But a general problem that I have faced in Custom Compare Function is that I have never understood its working. Sometimes, I make my own Custom Functions and they work but how- I don't understand. I read about it on Sort()-CPP Reference and Sort(): GeeksForGeeks but I did not understand its working. I wrote the following code:

```#define lpr pair<long long int,long long int>
#define S second
#define F first
#define ll long long int
bool comparefn(lpr a, lpr b)
{
if(a.S!=b.S)
return a.F<=b.F;
return false;
}
```

This is my custom compare function and I used it as:

```vector<lpr> a;
sort(a.begin(),a.end(),comparefn)```

It passed the first test case successfully but failed in the second one. On debugging I found that it fails for the following case:

```5 1 5
0 0 1```

I mean

```bool comparefn(lpr a, lpr b) {
if (a.S != b.S)
return a.F < b.F; // instead of <=
return false;
}```

STL implementations differ, but let us assume std::sort() is dispatched to insertion_sort() if the number of elements to be sorted is less than 10 (our case). So we have iterations like this:

```1: [3, 0]
2: is 2, 1 lt 3, 0 ? yes, so swap elements - > [2, 1 3, 0]
3.1: is 1, 1 lt 3, 0 ? yes, so swap elements - > [2, 1 1, 1 3, 0]
3.2: is 1, 1 lt 2, 1 ? no(second parts are equal, and comparefn() returns false in this
case) so elements are not swapped and data are not sorted as a result.```

Suggestion : 7

Another difference is that the list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable.,Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.,Both list.sort() and sorted() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons.,You can also use the list.sort() method. It modifies the list in-place (and returns None to avoid confusion). Usually it’s less convenient than sorted() - but if you don’t need the original list, it’s slightly more efficient.

`>>> sorted([5, 2, 3, 1, 4])[1, 2, 3, 4, 5]`
```>>> a = [5, 2, 3, 1, 4] >>>
a.sort() >>>
a[1, 2, 3, 4, 5]```
```>>> sorted({
1: 'D',
2: 'B',
3: 'B',
4: 'E',
5: 'A'
})[1, 2, 3, 4, 5]```
`>>> sorted("This is a test string from Andrew".split(), key = str.lower)['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']`
```>>> student_tuples = [
...('john', 'A', 15),
...('jane', 'B', 12),
...('dave', 'B', 10),
...
] >>>
sorted(student_tuples, key = lambda student: student[2]) # sort by age[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]```
```>>> class Student:
...self.name = name
...self.age = age
...def __repr__(self):
...

>>>
student_objects = [
...Student('john', 'A', 15),
...Student('jane', 'B', 12),
...Student('dave', 'B', 10),
...
] >>>
sorted(student_objects, key = lambda student: student.age) # sort by age[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]```

Suggestion : 8

May 10, 2022May 10, 2022

When you call the sort() method, with a custom compare function, the compare function is called on pairs in your to-be-sorted list, to determine the proper ordering in JavaScript.

```// Functionless
sort()

// Arrow function
sort((a, b) => {
/* ... */ })

// Compare function
sort(compareFn)

// Inline compare function
sort(function compareFn(a, b) {
/* ... */ })```

Note: the sort() method will give the right sorted array when sorting numbers. Using compare function can fix it.

```function compare(a, b) {
return a - b;
}```

Simple example code where compare function must take two arguments often referred to as a and b. Then you make the compare function return 0, greater than 0, or less than 0, based on these values, a and b.

```<!DOCTYPE html>
<html>
<body>
<script>
const num = [9, 10, 1, 5, 2, 10];
num.sort(function(a, b){return a - b});

console.log(num);
</script>
</body>
</html> ```

numbers

```var marks = [70, 90, 60, 80];
marks.sort(function(a, b) {
return a > b
}); //ascending , a < b descending . ```