简体   繁体   English

bubbleSort()用于Java中的int数组链接列表

[英]bubbleSort() for an int Array Linked List in Java

I'm having trouble with a bubbleSort method for my very unique homework assignment. 我为我非常独特的作业分配了bubbleSort方法,遇到了麻烦。

We are supposed to use a sorting method of our choice to sort, get this, a linked list of int arrays. 我们应该使用我们选择的排序方法对一个int数组的链接列表进行排序,获取。 Not an ArrayList not just a LinkedList. 不是ArrayList,而不仅仅是LinkedList。 It works like a linked list but the each Node contains an array of a capacity of 10 ints. 它像一个链表一样工作,但是每个Node包含一个容量为10 int的数组。

I am stuck on the sorting method. 我被卡在排序方法上。 I chose bubbleSort just because it was used in the last assignment and I felt most familiar with it. 我选择bubbleSort只是因为它在上一次作业中使用,并且我对它最熟悉。 Any tips for a better sorting method to try would be considered helpful as well. 尝试使用更好的排序方法的任何技巧也将被认为是有帮助的。

Here is my code: 这是我的代码:

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

This is a picture example of what I am supposed to be doing. 这是我应该做什么的图片示例。 可增长的数组链接列表

I have found a solution with selectionsort. 我找到了selectionsort的解决方案。 There are a few test values, just run it to see it. 有一些测试值,只需运行即可查看。 I can provide further information if needed. 如果需要,我可以提供更多信息。

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();
    }
}

} }

Here we go. 开始了。 The trivial solution consist in extracting all the elements of each array node and store them in a single big array, sort that big array (using Bubble Sort, Quick Sort, Shell Sort, etc.) and finally reconstruct the linked list of arrays with the the sorted values. 简单的解决方案包括提取每个数组节点的所有元素并将它们存储在单个大数组中,对该大数组进行排序(使用冒泡排序,快速排序,Shell排序等),最后使用排序的值。 I am almost sure that is not exactly what are you looking for. 我几乎可以肯定,这并不是您要找的东西。

If you want to sort the numbers in place , I can think of the following algorithm: 如果你想在地方的数字进行排序,我认为以下算法:

As others have commented, you need a comparison function that determines if a node A goes before a node B . 正如其他人所评论的那样,您需要一个比较函数来确定节点A是否位于节点B之前。 The following algorithm use the first idea but for each pair of nodes, eg A->[3, 9, 7] and B->[1, 6, 8] becomes [1, 3, 6, 7, 8, 9] and finally A->[1,3, 6] and B->[7, 8, 9] . 以下算法使用第一种方法,但对于每对节点,例如A->[3, 9, 7]B->[1, 6, 8]变为[1, 3, 6, 7, 8, 9]最后是A->[1,3, 6]B->[7, 8, 9] If we apply this rearrangement for each possible pair will end up with a sorted linked list of arrays (I have no proof, though). 如果我们对每个可能的对应用此重排,将最终得到数组的排序链表(不过,我没有证据)。

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()];
    }
}

This is kind of pseudo code because I haven't worked with linked lists in Java but I think you get the idea. 这是一种伪代码,因为我还没有使用Java中的链接列表,但是我想您明白了。

NOTE: I haven't tested the code, it may contain horrors. 注意:我尚未测试代码,它可能包含恐怖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM