![]() |
VOOZH | about |
Block sort is a sorting algorithm that sorts an array by dividing it into blocks of fixed size, sorting each block individually, and then merging the sorted blocks back into a single sorted array. Block sort is a good choice for sorting large datasets that do not fit in memory. It can efficiently sort data in blocks that fit in memory, and then merge the sorted blocks together to obtain the final sorted array.
Approach: The block sort approach is as follows:
- Divide the input array into blocks of fixed size.
- Sort each block using a comparison-based sorting algorithm (e.x., quicksort or mergesort).
- Merge the sorted blocks back into a single sorted array using a priority queue or min-heap.
Illustration:
Let the given array be: [1, 7, 8, 2, 3, 5, 4, 6]
- Let's choose a block size of 3. So we will divide the input into blocks of 3 integers each:
- Block 1: [1, 7, 8]
- Block 2: [2, 3, 5]
- Block 3: [4, 6]
- Now we sort each block individually using a comparison-based sorting algorithm. Let's use quicksort for this example. Here are the sorted blocks:
- Block 1: [1, 7, 8]
- Block 2: [2, 3, 5]
- Block 3: [4, 6]
- Now we merge the sorted blocks together. We create a min-heap that contains the first element from each block:
min-heap: [1, 2, 4]- We extract the minimum element from the heap, add it to the output array, and replace it with the next element from the block it came from. Continue until the heap is empty.
Iteration Details
- Extract 1 (minimum) from the heap, add it to the output:
- Output: [1]
- Replace 1 with the next element 7 from Block 1.
- Min-Heap: [2,7,4]
- Extract 2 (minimum) from the heap, add it to the output:
- Output: [1,2]
- Replace 2 with the next element 3 from Block 2.
- Min-Heap: [3,7,4]
- Extract 3 (minimum) from the heap, add it to the output:
- Output: [1,2,3]
- Replace 3 with the next element 5 from Block 2.
- Min-Heap: [4,7,5]
- Extract 4 (minimum) from the heap, add it to the output:
- Output: [1,2,3,4]
- Replace 4 with the next element 6 from Block 3.
- Min-Heap: [5,7,6]
- Extract 5 (minimum) from the heap, add it to the output:
- Output: [1,2,3,4,5]
- Replace 5 with the next element none (Block 2 is exhausted).
- Min-Heap: [6,7]
- Extract 6 (minimum) from the heap, add it to the output:
- Output: [1,2,3,4,5,6]
- Replace 6 with the next element none (Block 3 is exhausted).
- Min-Heap: [7]
- Extract 7 (minimum) from the heap, add it to the output:
- Output: [1,2,3,4,5,6,7]
- Replace 7 with the next element 8 from Block 1.
- Min-Heap: [8]
- Extract 8 (minimum) from the heap, add it to the output:
- Output: [1,2,3,4,5,6,7,8]
- Replace 8 with the next element none (Block 1 is exhausted).
- Min-Heap: []
- Final Output
The sorted array is: [1,2,3,4,5,6,7,8]
Input: [1, 7, 8, 2, 3, 5, 4, 6] Output: [1, 2, 3, 4, 5, 6, 7, 8]
Time Complexity: O(n*logn)
Auxiliary Space: O(1).