views:

60

answers:

1

This a question I found in the Wikipedia site (I want to learn sort algorithms very well). Anyway, this is a question - could you explain to me how I can show it?

Exercise: Show that Algorithm Insertion Sort (A) runs in time O(n + I) given that I is the number of inversions in the array A.

+3  A: 

Look at the Implementation and Analysis sections of this page.

Consider the algorithm presented there:

private static void insertionsort()
{
    int i, j, t;
    for (i=1; i<n; i++)
    {
        j=i;
        t=a[j];
        while (j>0 && a[j-1]>t)
        {
            a[j]=a[j-1];
            j--;
        }
        a[j]=t;
    }
}

Notice that the while loop runs for v[i] iterations, where v[i] is the number of inversions caused by element i. This should make the proof there very easy to understand.

IVlad
aha thanks a lot I read it ! I get it :)
also it seams that you know algorithms and every thing about data structure could I have your yahoo ID for more helping?? :)
Sorry, I don't use yahoo, but you can ask your questions on this site. That way you have much better chances of getting an answer quicker. Even if I don't know something, someone else definitely will.
IVlad
OK any way thanks
also can I use this algorithm for sorting characters?
Yes, you can. Characters are actually integers, so you can compare them just as you would compare integers.
IVlad
aha it means that the algorithm will compare their ASCII?
Yes, the algorithm will sort based on their ASCII codes.
IVlad
nice!! thanks a lot