
















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

















































Sorting 7-
EE 232 Data Structures Session-05 , Spring-
Sorting 7-
Sorting 7-
Sorting 7-
Each algorithm will be passed an array containing the elements and an integer containing the number of elements
We will assume that N , the number of elements passed to our sorting routines, has already been checked and is legal
Data will start at position 0 for all the sorts
Sorting 7-
The Algorithm
Insertion sort consists of N - 1 passes For pass P = 1 through N - 1 , insertion sort ensures that the elements in positions 0 through P are in sorted order
Insertion sort makes use of the fact that elements in positions 0 through P - 1 are already known to be in sorted order
In pass P , we move the element in position P left until its correct place is found among the first P + 1 elements
Sorting 7-
Example
Sorting 7-
Sorting 7-
Inversion
An ordered pair (i, j) such that i < j but a[i] > a[j]
Example
This is exactly the number of swaps that needed to be performed by insertion sort For a sorted array, number of inversions?
Sorting 7-
Theorem 2
Any algorithm that sorts by exchanging adjacent elements requires Ω( N ²) average time
The average number of inversions is N(N-1)/4 = Ω( N ²)
Sorting 7-
Sorting 7-
Algorithm…
After a phase, using some increment hk , for every
sorted
hk – sorted
Sorting 7-
void Shellsort( ElementType A[ ], int N ) { int i, j, Increment; ElementType Tmp; /* 1/ for( Increment = N / 2; Increment > 0; Increment /= 2 ) / 2/ for( i = Increment; i < N; i++ ) { / 3/ Tmp = A[ i ]; / 4/ for( j = i; j >= Increment; j -= Increment ) / 5/ if( Tmp < A[ j - Increment ] ) / 6/ A[ j ] = A[ j - Increment ]; else / 7/ break; / 8*/ A[ j ] = Tmp; } }
Sorting 7-
Worst-case Analysis
Theorem 1
Theorem 2
Sorting 7-