基于冒泡排序的链表排序 O(n²)
比较:
基于冒泡排序的链表排序,易懂,运行效率不高
基于归并排序的链表排序,效率高
LinkedListBobbleSort.java
package cn.stu.test;
public class LinkedListBobbleSort {
public static void main(String[] args) {
LinkNode i1 = new LinkNode(98);
LinkNode i2 = new LinkNode(34);
LinkNode i3 = new LinkNode(43);
LinkNode i4 = new LinkNode(11);
LinkNode i5 = new LinkNode(44);
LinkNode i6 = new LinkNode(54);
LinkNode i7 = new LinkNode(12);
i1.next = i2;
i2.next = i3;
i3.next = i4;
i4.next = i5;
i5.next = i6;
i6.next = i7;
i7.next = null;
LinkNode node = i1;
while(node != null){
System.out.print(node.num+" ");//输出未排序的链表
node = node.next;
}
System.out.println();
System.out.println("----------------------------");
node = sortBobble(i1);//冒泡排序
while(node != null){
System.out.print(node.num+" ");//输出经过排序的链表
node = node.next;
}
}
public static int lengthList(LinkNode link){
int num = 0;
while(link != null){
num++;
link = link.next;
}
return num;
}
public static LinkNode sortBobble(LinkNode link) {
int i,j,k;
int len = lengthList(link);
LinkNode p = null;
LinkNode q = null;
for(i=0,p = link;i<len-1;i++,p = p.next)
{
for(j=i+1,q = p.next;j<len;j++,q = q.next)
{
if(p.num < q.num)
{
k = p.num;
p.num = q.num;
q.num = k;
}
}
}
return link;
}
}