Sorting List using custom sorting technique

How to sort custom Objects using Bubble Sort ? (Example:1)

package com.gs.corejava.collections;

interface MyComparable<T> {
	int myCompareTo(T object);
}

class Doctor implements MyComparable<Doctor> {
	private int id;
	private int age;
	private String name;

	/**
	 * @param id
	 * @param age
	 * @param name
	 */
	public Doctor(int id, int age, String name) {
		super();
		this.id = id;
		this.age = age;
		this.name = name;
	}

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}

	/**
	 * @param age
	 *            the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Doctor [id=" + id + ", age=" + age + ", name=" + name + "]";
	}

	@Override
	public int myCompareTo(Doctor doctor) {
		if (this.getId() - doctor.getId() == 0) {
			return this.getAge() - doctor.getAge();
		} else {
			return this.getId() - doctor.getId();
		}
	}

}

class MyCollections {
	/**
	 * @param <T>
	 * @param arr
	 */
	public static <T extends MyComparable<T>> void bubbleSort(T[] arr) {
		T c;
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr.length - i - 1; j++) {
				if (arr[j].myCompareTo(arr[j + 1]) >= 0) {
					c = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = c;
				}
			}
		}
	}
}

public class BubbleSort {

	public static void main(String[] args) {

		Doctor doctor = new Doctor(1, 65, "Mohit");
		Doctor doctor1 = new Doctor(4, 26, "Rohit");
		Doctor doctor2 = new Doctor(2, 23, "Amit");
		Doctor doctor3 = new Doctor(6, 45, "Sumit");
		Doctor doctor4 = new Doctor(2, 21, "Pooja");

		Doctor[] doctors = { doctor, doctor1, doctor2, doctor3, doctor4 };
		MyCollections.bubbleSort(doctors);
		for (int i = 0; i < doctors.length; i++) {
			System.out.println(doctors[i]);
		}
	}

}

Example 2:

Last updated

Was this helpful?