I was trying another approach of sorting a linked list. Aside from the available methods, I've decided to take each node from the linked list and place it into an array. With that, I would be able to compare the data variables easily. I applied quickSort()
on the array, and this is what I have. I would appreciate any feedback/comments on my code.
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
Student s = new Student(1, "John", 20, "Italy", "2011");
list.addStudent(s);
Student s2 = new Student(2, "Mark", 19, "UAE", "2010");
list.addStudent(s2);
Student s3 = new Student(3, "Sally", 35, "UAE", "2000");
list.addStudent(s3);
System.out.println("Students in the list: ");
list.print();
Node[] n = list.convertA(list);
quickSort(n, 0, (n.length-1));
System.out.println("Sorted list is:");
for(int q =0;q<n.length;q++){
System.out.println(n[q] + " ");
}
}
public static int partition(Node arr[], int left, int right) {
int i = left, j = right;
Node tmp;
Node pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i].getStudent().getAge() < pivot.getStudent().getAge()) {
i++;
}
while (arr[j].getStudent().getAge() > pivot.getStudent().getAge()) {
j--;
}
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
return i;
}
public static void quickSort(Node arr[], int left, int right) {
int index = partition(arr, left, right-1);
if (left < index - 1) {
quickSort(arr, left, index - 1);
}
if (index < right) {
quickSort(arr, index, right);
}
}