[英]Inbuilt java sorting algorithms for array/linked lists that uses Quicksort
[英]Linked Lists & quickSort
我正在嘗試另一種對鏈表進行排序的方法。 除了可用的方法外,我決定從鏈接列表中取出每個節點並將其放置在數組中,這樣我就可以輕松比較數據變量。 我在數組上應用了quickSort,這就是我得到的...但是,當顯示結果時,我得到的是節點的內存地址,而不是學生信息
出現的內容是:(作為輸出)
排序列表是:
homework2.Node@44b471fe
homework2.Node@22a7fdef
homework2.Node@431067af
homework2.Node@6a07348e
null
這是我的代碼。
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);
}
}
Node類如下:
public class Node {
private Student student;
public Node link;
public Node() {
student = null;
link = null;
}
public Node(Student s) {
student = s;
}
public Node(Student s, Node l) {
student = s;
link = l;
}
public Object getData() {
return student.toString();
}
public Student getStudent() {
return student;
}
public void setLink(Node link) {
this.link = link;
}
public void setStudent(Student student) {
this.student = student;
}
@Override
public String toString() {
return this.student.toString();
}
}
但是,當顯示結果時,我得到的是節點的內存地址,而不是學生信息
因為您沒有在Node
類中重寫toString
方法,所以您將打印在Object
類中定義的該方法的默認行為:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
首先,您必須在Student
類中重寫toString
方法:
@Override
public String toString (){
return this.id+"-"+this.name+"-"+this.age+"-"+this.country+"-"+this.year;
}
然后,您可以在Node類中重寫toString方法:
@Override
public String toString (){
return this.student.toString();
}
然后讓您的for循環像這樣。
或者只是重寫Student類中的toString
方法:
並像這樣修改您的for循環:
for(int q =0;q<n.length;q++){
System.out.println(n[q].getStudent() + " ");
}
我已經解決了問題,並對數組進行了排序,
我的quickSort方法中存在一個問題..對於索引,它應該是:
int index = partition(arr,left,right)
代替 :
int index = partition(arr, left, right-1);
正如鄒鄒之前指出的,for循環有問題,所以我也修復了
非常感謝您的幫助 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.