Sorting a linked list

前端 未结 8 747
-上瘾入骨i
-上瘾入骨i 2020-11-29 09:26

I have written a basic linked list class in C#. It has a Node object, which (obviously) represents every node in the list.

The code does not use IEnumerable, however

8条回答
  •  半阙折子戏
    2020-11-29 10:06

    If you want to really utilize the fact that you're using a linked list, as opposed to working around it, I would suggest insertion sort.

    Normally an insertion sort is not very efficient - O(n^2) in the worst case, but with linked list this can be improved to O(n log n)

    pseudo:

    for i in range (1,n):
        item = arr[i]
        location = binary_search(l=root, r=i, value=item.val)  // O(log i)
        insert_item_before(arr[location], item) // O(1)
    

    In the regular algorithm the insert part takes O(i) because we may need to shift all the items that are larger then item. because a linked list enables us to do the insertion without shifting, we can search for the location with a binary search and so the insertion part takes only O(log i)

    note: usually an insertion sort has O(n) performance in the best case (if the array is sorted). Unfortunately this isn't the case here because binary search takes always O(log n) steps.

提交回复
热议问题