how to sort data at the time of adding it, not later?

后端 未结 4 1879
醉话见心
醉话见心 2021-01-21 18:29

I am new to algorithms so please forgive me if this sounds basic or stupid.

I want to know this : instead of adding data into some kind of list and then performing a sor

相关标签:
4条回答
  • 2021-01-21 18:44

    There are basically two different methods to insert a value in a list, which you use depend a bit on what kind of list you are using:

    • Use binary search to locate where the value should be inserted, and insert the value there.

    • Loop from the end of the list, moving all higher values one step up, and put the value in the gap before the lowest higher value.

    The first method would typically be used if you are using a binary tree or a linked list, where you don't have to move items in the list to do the insert.

    0 讨论(0)
  • 2021-01-21 18:44

    Yes but that's usually slower than adding all the data and sorting it afterwards because to insert the data as it is added, you need to traverse the list every time you add an element.

    With binary search, you need not look at every element but even then, you often need to get more elements from the list as when you sort afterwards.

    So from a performance view, sorted insert is inferior to post sorting.

    0 讨论(0)
  • 2021-01-21 18:46

    If you use a binary search tree instead of an array, the sorting would happen "automatically", because it's already done by the insert method of the nodes. So a binary tree is always sorted, and it's easy to traverse. The only problem is that when you have already (more or less) sorted data, the tree becomes inbalanced (which is where red-black-trees and other variations come into play).

    0 讨论(0)
  • 2021-01-21 19:08

    You want to maintain a sorted array at all times, so you shall find a correct place in sequence for every new element you want to add to the array. This can be done efficiently (O(logn) complexity) by utilizing a modified binary search algorithm.

    0 讨论(0)
提交回复
热议问题