Reputation: 11441
I am reading algorithms by Robertsedwick by C++ on sorting
Property 1: Insertion sort and bubble sort use a linear number of comparisions and exchanges for files with at most a constant number of inversions corresponding to each element.
In another type of partially sorted file, we perhaps have appended a few elements to a sorted file or have edited a few elements in a sorted file to change their kesy. Insetion sort is efficient menthod for such files; bubble and selection sort are not.
Property 2: Insertion sort uses a linear number of comparisions and exchanges for files with atmost a constant number of elements having more than a constant number of corresponding inversions.
My questions on above properties are
I am not able to get difference between property 1 and property 2? Can any one explain me here?
On what basis above for property 2 author mentioned insertion sort is best and not bubble and selection sort?
It would be good if explained with example.
Thanks for your time and help
Upvotes: 0
Views: 2374
Reputation: 26446
So, an inversion where the sort order is <
is there i < j
but a[i] > a[j]
.
Property 1. Consider the sequence 2 1 4 3 6 5 8 7 10 9...
. Every element is out of order with respect to its neighbor to the left or to the right, but is in order with respect to all other elements. So each element has a constant number of inversions, one, in this case. This property says that all the elements can be a little out of order.
Both bubble sort and insertion sort will run in linear time. Bubble sort will take just one pass to correct the order since it swaps neighboring elements and another pass to confirm. Insertion sort will only have to do one compare and swap per element.
Property 2. This property is stronger. In addition to being able to have all the elements a little out of order, now you can have a few that are very out of order. Consider the same sequence as before, but the smallest element and largest elements moved to opposite ends: n 2 4 3 6 5 8 7 10 9...1
. Now 1
and n
are out of order with respect to all other elements.
Insertion sort will still perform in linear time. As before, most of the elements require only a few compare and swaps, but there are a few that can take order n
compare and swaps. In this example, the first n-1
elements take a couple of compare and swaps (ok, so the 2
only takes one) to get into place and the last takes n-1
compare and swaps -- 2*(n-1) + 1*(n-1)
is order n
.
Bubble sort has a much harder time in this example. Each pass through can only move the 1
a single step backwards. Thus it will take at least (n-1)
passes in which (n-1)
comparisons are done before completion -- this is multiplicative (n-1)*(n-1)
is order n^2
. (You could also run bubble sort in the opposite direction, in which case the largest element at the beginning would slowly move to the other end instead.)
Upvotes: 3