【问题标题】:bubbleSort() for an int Array Linked List in JavabubbleSort() 用于 Java 中的 int 数组链表
【发布时间】: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 SortMerge Sort 以获得更好的排序算法(两者都是 O(nlog(n)) 而不是 O(n^2) 的冒泡排序) ,或者如果您不需要自己编写,您可以随时使用 Arrays.sort。
  • @MagdaleneB。好吧,这就是您的数组链表的工作方式,但是您正在尝试对数字进行排序,这是您的问题吗?:输入:[9, 3, 2] -&gt; [11, 12, 4] -&gt; [21, 0, 85] -&gt; ... -&gt; [88, 100, 7] 输出:[0, 2, 3] -&gt; [4, 7, 9] -&gt; [11, 12, 21] -&gt; ... [85, 88, 100]

标签: java arrays


【解决方案1】:

我找到了选择排序的解决方案。有几个测试值,运行看看就知道了。 如果需要,我可以提供更多信息。

import java.util.ArrayList;
import java.util.Random;

public class ArrayedListSort {

int listsize = 5;  // how many nodes
int maxValue = 99; // the highest value (0 to this)
int nodeSize = 3;  // size for every node

public static void main(String[] args) {
    // run non static
    new ArrayedListSort().runTest();
}

/**
 * Log function.
 */
public void log(Object s) {
    System.out.println(s);
}
public void logNoBR(Object s) {
    System.out.print(s);
}

/**
 * Output of list we have.
 */
public void logMyList(ArrayList<ListNode> listNode, String name) {
    log("=== LOG OUTPUT " + name + " ===");
    for ( int i=0; i < listNode.size(); i++) {
        logNoBR(" node <" + i + ">");
        logNoBR(" (");
        for (int j=0; j < listNode.get(i).getSize(); j++) {
            if ( j != (listNode.get(i).getSize()-1)) // if not last add ","
                logNoBR( listNode.get(i).getValueAt(j) + "," );
            else
                logNoBR( listNode.get(i).getValueAt(j) );
        }
        log(")");
    }
    log("=====================================\n");
}

public void runTest() {
    // create example List

    ArrayList<ListNode> myList = new ArrayList<ListNode>();

    // fill the nodes with random values
    for ( int i = 0; i < listsize; i++) {
        myList.add(new ListNode(nodeSize));
        for (int j=0; j < nodeSize; j++) {
            int randomValue = new Random().nextInt(maxValue);
            myList.get(i).addValue(randomValue);
        }
    }
    logMyList(myList, "myList unsorted"); // to see what we have

    // now lets sort it
    myList = sortListNode(myList);

    logMyList(myList, "myList sorted"); // what we have after sorting
}

/**
 *  Selectionsort 
 */
public ArrayList<ListNode> sortListNode(ArrayList<ListNode> myList) {
    ArrayList<ListNode> retList = new ArrayList<ListNode>();
    for ( int i = 0; i < listsize; i++) {
        retList.add(new ListNode(nodeSize));
    }
    int lastSmallest = myList.get(0).getValueAt(0);

    while ( !myList.isEmpty() ) {
        int lastJ=0, lastI=0;
        for ( int i = 0; i < myList.size(); i++) {
            for (int j=0; j < myList.get(i).getSize(); j++) {
                if ( myList.get(i).getValueAt(j) <= lastSmallest ) {
                    lastSmallest = myList.get(i).getValueAt(j);
                    lastJ = j;
                    lastI = i;
                    //log("Found smallest element at <"+i+","+j+"> (" + lastSmallest + ")");
                }
            }
        }
        myList.get(lastI).removeValue(lastJ);

        if ( myList.get(lastI).getSize() == 0 )
            myList.remove(lastI);

        // add value to new list
        for ( int i = 0; i < listsize; i++) {
            if ( retList.get(i).getSize() < retList.get(i).getMaxSize() ) {
                retList.get(i).addValue(lastSmallest);
                break;
            }
        }
        lastSmallest = Integer.MAX_VALUE;

    }
    return retList;
}

public class ListNode {
    private ArrayList<Integer>  values  = new ArrayList<Integer>();
    private  int                    maxSize;

    public ListNode(int maxSize) {
        this.maxSize = maxSize;
    }
    public ArrayList<Integer> getValues() {
        return values;
    }
    public int getMaxSize() {
        return maxSize;
    }
    public int getSize() {
        return values.size();
    }
    public int getValueAt(int position) {
        if ( position < values.size())
            return values.get(position);
        else
            throw new IndexOutOfBoundsException();
    }
    public void addValue(int value) {
        values.add(value);
    }
    public void removeValue(int position) {
        if ( position < values.size()) {
            values.remove(position);                    
        } else
            throw new IndexOutOfBoundsException();
    }
}

}

【讨论】:

    【解决方案2】:

    我们开始吧。简单的解决方案包括提取每个数组节点的所有元素并将它们存储在一个大数组中,对该大数组进行排序(使用冒泡排序、快速排序、壳排序等),最后用排序后的值。我几乎可以肯定这不是你要找的。​​p>

    如果你想就地对数字进行排序,我可以想到以下算法:

    正如其他人评论的那样,您需要一个比较函数来确定节点 A 是否在节点 B 之前。以下算法使用第一个想法,但对于每对节点,例如A-&gt;[3, 9, 7]B-&gt;[1, 6, 8] 变为 [1, 3, 6, 7, 8, 9],最后变为 A-&gt;[1,3, 6]B-&gt;[7, 8, 9]。如果我们对每个可能的对应用这种重新排列,最终将得到一个排序的数组链表(不过我没有证据)。

    A = head;
    while (A.hasNext()) {
        arrayA = A.getArray();
        B = A.getNext();
        while (B.hasNext()) {
            arrayB = B.getArray();
    
            // concatenate two arrays
            int[] C = new int[arrayA.size() + arrayB.size()];
            int i;
            for (i = 0; i < arrayA.size(); i++)
                C[i] = arrayA[i];
            for ( ; i < arrayA.size() + arrayB.size(); i++)
                C[i] = arrayB[i-arrayA.size()];
    
            // sort the new arrays using agains Bubble sort or any
            // other method, or Arrays.sort()
            Arrays.sort(C);
    
            // now return the sorted values to the two arrays
            for (i = 0; i < arrayA.size(); i++)
                arrayA[i] = C[i];
            for (i = 0; i < arrayB.size(); i++)
                arrayB[i] = C[i+arrayA.size()];
        }
    }
    

    这是一种伪代码,因为我没有使用过 Java 中的链表,但我想你明白了。

    注意:我没有测试过代码,它可能包含恐怖内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-06
      • 2021-11-28
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多