【发布时间】:2017-07-09 07:22:34
【问题描述】:
我使用 LinkedList 实现了冒泡排序,如下所示。我无法为这个问题找到正确有效的解决方案。此代码需要进行哪些更改才能有效地工作。如果有人在链表上有更好、更有效的冒泡排序实现,请提供。
class SortList {
int size;
Node head;
class Node{
int data;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
Node(){
this.data = 0;
this.next = null;
}
}
public void push(int d) {
Node newNode = new Node();
newNode.data = d;
newNode.next = head;
head = newNode;
size++;
}
public void display(){
Node n = head;
while(n!=null){
System.out.print(n.data +" ");
n = n.next;
}
}
public int getLength(){
int count=0;
Node n = head;
while(n!=null){
count++;
n = n.next;
}
return count;
}
public int getLengthR(Node n){
if(n==null) return 0;
return 1+getLengthR(n.next);
}
public int getL(){
return getLengthR(head);
}
public static void main(String[] args) {
SortList ls = new SortList();
int[]arrList = {5,2,7,3,1,2};
for(int i=0;i<arrList.length;i++){
ls.push(arrList[i]);
}
ls.display();
ls.sortList();
ls.display();
}
public void sortList(){
if(size > 1){
Node node = head;
Node nextNode = head.next;
for(int i=0;i<size;i++){
for(int j=0;j<size - i - 1;j++){
while(node.data > nextNode.data){
Node temp =node;
node = nextNode;
nextNode = temp;
}
node = nextNode;
nextNode = nextNode.next;
}
}
}
}
}
【问题讨论】:
-
“我没有得到排序列表”——这还不足以描述问题。您是否在 IDE 调试器中单步执行了代码?你能确定哪里出了问题吗?显示一些示例输入、预期输出和实际输出。
-
您可以使用简单的google search找到答案。
-
输入已经存在,int[]arrList = {5,2,7,3,1,2};当我显示结果时,我在排序之前和排序之后得到相同的输出。
标签: java sorting linked-list bubble-sort