Content deleted Content added
m →Pseudocode: : remove trailing ")" |
|||
(13 intermediate revisions by 8 users not shown) | |||
Line 1:
{{Short description|Sorting algorithm}}
{{refimprove|date=October 2017}}
{{Infobox Algorithm
Line 5 ⟶ 6:
|data=[[Array data structure|Array]]
|time=<math>O(n^2)</math>
|best-time=<math>O(n\log n)</math>
|average-time=<math>O(n\log n)</math>
|space=<math>O(n)</math>
|optimal=?
}}
'''Library sort'''
<blockquote>Suppose a librarian were to store
The algorithm was proposed by [[Michael A. Bender]], [[Martín Farach-Colton]], and [[Miguel Mosteiro]] in 2004<ref>{{cite
Like the insertion sort it is based on, library sort is a
Compared to basic insertion sort, the drawback of library sort is that it requires extra space for the gaps. The amount and distribution of that space would
Another drawback is that it cannot be run as an [[online algorithm]], because it is not possible to randomly shuffle the input. If used without this shuffling, it could easily degenerate into quadratic behaviour.
One weakness of [[insertion sort]] is that it may require a high number of swap operations and be costly if memory write is expensive. Library sort may improve that somewhat in the insertion step, as fewer elements need to move to make room, but is also adding an extra cost in the rebalancing step. In addition, locality of reference will be poor compared to [[mergesort]] as each insertion from a random data set may access memory that is no longer in cache, especially with large data sets.▼
▲One weakness of [[insertion sort]] is that it may require a high number of swap operations and be costly if memory write is expensive. Library sort may improve that somewhat in the insertion step, as fewer elements need to move to make room, but
==Implementation==
Line 29 ⟶ 32:
# '''Binary Search''': Finding the position of insertion by applying binary search within the already inserted elements. This can be done by linearly moving towards left or right side of the array if you hit an empty space in the middle element.
# '''Insertion''': Inserting the element in the position found and swapping the following elements by 1 position till an empty space is hit. This is done in logarithmic time, with high probability.
# '''Re-Balancing''': Inserting spaces between each pair of elements in the array.
===Pseudocode===
Line 36 ⟶ 39:
'''procedure''' rebalance(A, begin, end) '''is'''
r ← end
w ← end
'''while''' r ≥ begin '''do'''
A[w+1] ← gap▼
A[w] ← A[r]
r ← r − 1
w ← w − 2
Line 48 ⟶ 51:
S ← new array of n gaps
'''for''' i ← 1 to floor(log2(n
'''for'''
ins ← binarysearch(A[j], S, 2^i)
insert A[j] at S[ins]
Line 63 ⟶ 67:
{{sorting}}
[[Category:Comparison sorts]]
[[Category:Stable sorts]]
|