Friday 28 February 2014

Library Sort

Library Sort
Library sort, or gapped insertion sort is a sorting algorithm that uses an insertion sort, but with gaps in the array to accelerate subsequent insertions. The name comes from an analogy:[1]
Suppose a librarian were to store his books alphabetically on a long shelf, starting with the A's at the left end, and continuing to the right along the shelf with no spaces between the books until the end of the Z's. If the librarian acquired a new book that belongs to the B section, once he finds the correct space in the B section, he will have to move every book over, from the middle of the B's all the way down to the Z's in order to make room for the new book. This is an insertion sort. However, if he were to leave a space after every letter, as long as there was still space after B, he would only have to move a few books to make room for the new one. This is the basic principle of the Library Sort.
The algorithm was proposed by Michael A. BenderMartín Farach-Colton, and Miguel Mosteiro in 2004[2] and published 2006.[3]

Library sort
Class
Data structure













Algorithm
Let us say we have an array of n elements. We choose the gap we intend to give. Then we would have a final array of size (1 + ε) n. The algorithm works in log n rounds. In each round we insert as many elements as there are in the final array already, before re-balancing the array. For finding the position of inserting, we apply Binary Search in the final array and then swap the following elements till we hit an empty space. Once the round is over, we re-balance the final array by inserting spaces between each element.
Following are three important steps of the algorithm:
1. 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.
2. Insertion: Inserting the element in the position found and swapping the following elements by 1 position till an empty space is hit.

3. Re-Balancing: Inserting spaces between each pair of elements in the array. Here we have used a queue to accomplish this. This takes linear time, and because there are log n rounds in the algorithm, total re-balancing takes O(n log n) time only.

No comments:

Post a Comment