【发布时间】:2014-02-13 19:53:01
【问题描述】:
我的非常独特家庭作业的冒泡排序方法有问题。
我们应该使用我们选择的排序方法来排序,得到这个,一个 int 数组的链表。不是 ArrayList 不仅仅是 LinkedList。它的工作方式类似于链表,但每个节点包含一个容量为 10 个整数的数组。
我卡在排序方法上。我之所以选择bubbleSort,是因为上次作业中用到了它,而且我觉得它最熟悉。尝试更好的排序方法的任何提示也会被认为是有帮助的。
这是我的代码:
public void bubbleSort() {
current = head; // Start at the head ArrayNode
for (int i = 0; i < size; i++) { // iterate through each ArrayNode
currentArray = current.getArray(); // get the array in this ArrayNode
int in, out;
for (out = size-1; out > 1; out--) { // outer loop (backwards)
for (in = 0; in < out; in++) { // inner loop (forwards)
if (currentArray[in] > currentArray[in+1]) // out of order?
swap(in, in+1); // swap them!
}
}
current.setArray(currentArray);
current = current.getNext();
}
}// End bubbleSort() method
// A helper method for the bubble sort
private void swap(int one, int two) {
int temp = currentArray[one];
currentArray[one] = currentArray[two];
currentArray[two] = temp;
} // End swap() method
这是我应该做的一个图片示例。
【问题讨论】:
-
对不起,你在整理什么?
-
数组中包含在节点中的整数(如来自链表)。每个节点都有一个 10 个整数的数组。
-
那么你/你应该如何对数组进行排序?按长度?比较每个元素?
-
您可能需要查看 Quick Sort 或 Merge Sort 以获得更好的排序算法(两者都是 O(nlog(n)) 而不是 O(n^2) 的冒泡排序) ,或者如果您不需要自己编写,您可以随时使用 Arrays.sort。
-
@MagdaleneB。好吧,这就是您的数组链表的工作方式,但是您正在尝试对数字进行排序,这是您的问题吗?:输入:
[9, 3, 2] -> [11, 12, 4] -> [21, 0, 85] -> ... -> [88, 100, 7]输出:[0, 2, 3] -> [4, 7, 9] -> [11, 12, 21] -> ... [85, 88, 100]。