简体   繁体   中英

Sorting a linked list using insertion sort

I have to design my own insertion sort but I'm using javas linked list.

private static void insertionSort( LinkedList<Integer> data, int first, int last ){
    System.out.println("insertion sort");
    ListIterator itr = data.listIterator(first+1);
    int count = first+1;
    while (count<=last){//itr.hasNext() &&  
        ListIterator itr2 = data.listIterator(itr.nextIndex()-1);
        int tmp = (Integer) itr.next();
        while( itr2.hasPrevious() && tmp < (Integer)itr2.previous()){
            itr2.next();
            itr2.set(itr2.previous());
        }
        data.set(itr2.nextIndex(), tmp);
        count++;
    }

it will eventually be sorting parts of the linked list, however for now im just passing it the whole list and trying. it seems to be inserting into the list however it dosn't move the things in the list back. I feel like I'm really close. does anyone have any pointers?

I believe that in you implementation you are doing some "weird" things with the iterators, when you call set . The use of them for such applications is not "that" necessary, since the LinkedList class provides methods like size , get , and set .

Based on what you were trying to do and looking at the insertion sort algorithm pseudocode here , I wrote this method:

public static void insertionSort(LinkedList<Integer> linkedList, int first, int last) {
        for (int i = 2; i <= last; i++) {
            for (int k = i; k > first
                    && (linkedList.get(k - 1) < linkedList.get(k - 2)); k--) {
                Integer temp = linkedList.get(k - 2);
                linkedList.set(k - 2, linkedList.get(k - 1));
                linkedList.set(k - 1, temp);
            }
        }
    }

However, this method has two restrictions has two restrictions:

  1. 1 <= first
  2. last <= linkedList.size()

Examples:

Sorting the entire linked list:
Input: LL = [2, 1, 8, 6, 4, 0, 3, 9, 5, 7]
Call: insertionSort(LL, 1, ll.size())
Output: [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]

Sorting the first four elements in the linked list:
Input: LL = [2, 1, 8, 6, 4, 0, 3, 9, 5, 7]
Call: insertionSort(LL, 1, 4)
Output: [ 1 , 2 , 6 , 8 , 4, 0, 3, 9, 5, 7]

Sorting the last 2 elements in the linked list:
Input: LL = [2, 1, 8, 6, 4, 0, 3, 9, 5, 7]
Call: insertionSort(LL, 9, LL.size())
Output: [2, 1, 8, 6, 4, 0, 3, 9, 5 , 7 ]

Sorting 4 elements within the linked list:
Input: LL = [2, 1, 8, 6, 4, 0, 3, 9, 5, 7]
Call: insertionSort(LL, 3, 6)
Output: [2, 1, 0 , 4 , 6 , 8 , 3, 9, 5, 7]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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