On referring Insertion sort lecture taught by Sedgewick,
I learnt that,
Proposition: To sort a randomly-ordered array with distinct keys, insertion sort uses ~(1/4 )N^2 compares and ~(1/4 )N^2 exchanges on average.
I also learnt that,
Best case - If the array is in ascending order, Insertion sort makes N-1 compares and zero exchanges
If I analyse the pseudo code,
int n = array.length;
for(int i=0; i < n; i++){
for(int j=i; j>0; j--){
if(less(a[j], a[j-1]))
swap(array, j, j-1);
else
break; // Is N^2/4 due to break statement?
}
}
Question:
So,
Due to break
statement to avoid further comparisons, insertion sort performs (N^2)/4 comparisons in average case and N-1 comparisons, in best case.
Is my understanding correct?
Ah a little more math is needed.
Did you Realize that number of swaps performed by insertion sort is exactly the number of inversions present in the input ?
Inversion: index pair (i,j) is an inversion if
i<j but a[i]>a[j]
.How many indices are there with i
Btw I guess you know this...but still.why 1+2+..n-1=n*(n-1)/2