Compare pairs in java

If there is a Pair class:
class Pair {
int x;
int y;

// Constructor 

public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
}

Why this gives me sorted Pair
public int compare(Pair a, Pair b)
{

            return a.y-b.y;
         }

rather than this
public int compare(Pair a, Pair b)
{
if( a.y > b.y)
return 1;
else
return 0;
}

That’s how the comparator works in Java.
This is a general programming principle and applies in almost all programming languages.

You can go through these links to understand it in detail:-

You can use any of the logic for Comparison. Both of them works fine.

Eg :

public class Doubt {

public static void main(String[] args) {

	Pair[] pairs = new Pair[6];

	pairs[0] = new Pair(10, 30);
	pairs[1] = new Pair(5, 20);
	pairs[2] = new Pair(7, 10);
	pairs[3] = new Pair(8, 40);
	pairs[4] = new Pair(90, 5);
	pairs[5] = new Pair(55, 500);

	// bubble sort logic
	for (int i = 0; i < pairs.length - 1; i++) {
		for (int j = 0; j < pairs.length - i - 1; j++) {

			if (compare(pairs[j], pairs[j + 1]) > 0) {

				Pair temp = pairs[j];
				pairs[j] = pairs[j + 1];
				pairs[j + 1] = temp;
			}

		}
	}

	// display the pairs array
	for (Pair p : pairs) {
		System.out.println(p);
	}

}

public static int compare(Pair a, Pair b) {
	// return a.y - b.y;

	if (a.y > b.y)
		return 1;
	else
		return 0;
}

}

class Pair {
int x;
int y;

// Constructor
public Pair(int x, int y) {
	this.x = x;
	this.y = y;
}

@Override
public String toString() {
	return "X:" + this.x + " Y:" + this.y;
}

}

2 Likes