Goodday! I am trying to sort a data (Name - age) by its age. I have use the QUICKSORT algorithm and works fast for sorting AGEs but how do I sort Age with their respective name?
I also googled the Comparable and Comparator but I don't understand how to implement it with quicksort.
here is my code for quicksort.
private int array[];
private int length;
public void sort(int[] inputArr) {
if (inputArr == null || inputArr.length == 0) {
return;
}
this.array = inputArr;
length = inputArr.length;
quickSort(0, length - 1);
}
private void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
swap(i, j);
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
}
private void swap(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String a[]){
GUIAdvanceSort sorter = new GUIAdvanceSort();
int[] input = {5,4,3,2,1};
sorter.sort(input);
for(int i:input){
System.out.print(i);
System.out.print(" ");
}
}
<and>operators work on ints in the array but not objects. You need to invoke a Comparator on the two objects to get the same information.Collections.sort(myList, new MySpecialNameAndAgeComparator());. See: docs.oracle.com/javase/8/docs/api/java/util/…