【发布时间】:2020-02-09 23:53:11
【问题描述】:
我有一个冒泡排序,它适用于从文件中的数据创建的链表。如果数字小于我的起始头节点,我的排序算法将不起作用。如何更新我的代码来解决这个问题?
示例:如果我的列表是 3、1、8、5 它将打印 3 --> 5 --> 8 并且 1 无处可见
public void bubbleSort(LinkedNode head) {
LinkedNode previous;
LinkedNode current;
LinkedNode next;
boolean isSorted = true;
//if list is empty or only 1 item is in list -> it is sorted
if (head == null || head.getNext() == null) {
return;
}
long start = System.currentTimeMillis(); //begin count for bubbleSort
while(isSorted) {
bubbleComparisons = 0;
bubbleExchanges = 0;
previous = null;
current = head;
next = head.getNext();
isSorted = false;
while(next != null) {
bubbleComparisons ++; //increment counter for each comparison made
if (current.getElement() > next.getElement()) {
if (head == current) {
head = next;
}
else {
previous.setNext(next);
}
current.setNext(next.getNext());
next.setNext(current);
isSorted = true;
current = next;
bubbleExchanges++;
}
previous = current;
current = previous.getNext();
next = current.getNext();
}
【问题讨论】:
标签: java linked-list bubble-sort