An Application of Bubble Sort

阅读更多
This problem is inspired by the discussion about ordering specification, BSort 
in the paper "Aurora: a new model and architecture for data stream management" 

Problem: 
There is an array A whose size is n. there is a ascending sorting with some 
disorder in A. The disorder is specified as this: 

For any element, there are at most 2 bigger preceding elements. In other words, 
for A[i], A[i_1] > A[i], ..., A[i_m] > A[i] (i_1 > i, ..., i_m > i). m <= 2. 

Design an algorithm to remove the disorder in A. 

NOTE: 2 can be generalized to m. 

Solution: 
Run 2 bubble sort pass over A. 

--------------- 
| | | |X| | | | 
--------------- 
         ^ 
         i 
Since A[i-1] is the biggest element among the A[0..i-1],  A[i-1] must be among 
the 2 preceding elements which are bigger than A[i]. If A[i] >= A[i-1], there 
will no preceding bigger elements for A[i]. Otherwise, switch A[i] with A[i-1].  
There will be at most 1 preceding element for A[i-1]. So after the first pass, 
for any element, there is at most 1 bigger preceding element. 

Apply the similar analysis to pass 2. After the second pass, for any element, 
there is at most 0 bigger preceding element. In other words, A is sorted. 

你可能感兴趣的:(An Application of Bubble Sort)