Sorting: Spring Semester 2011 Programming and Data Structure 17
Sorting: Spring Semester 2011 Programming and Data Structure 17
• Original list:
10, 30, 20, 80, 70, 10, 60, 40, 70
• What we want ?
– Sort the given data sorted in the specified order
size-1
0
x: Unsorted list
Sorted list
• General situation :
0 k size-1
x: smallest elements, sorted remainder, unsorted
•Step :
•Find smallest element, mval, in x[k..size-1]
•Swap smallest element with x[k], then
increase k by one.
0 k mval size-1
swap
Spring Semester 2011 Programming and Data Structure 22
An example worked out
PASS 1:
10 5 17 11 -3 12 Find the minimum
10 5 17 11 -3 12 exchange with 0th
-3 5 17 11 10 12 element
PASS 2:
-3 5 17 11 10 12 Find the minumum
-3 5 17 11 10 12 exchange with 1st
-3 5 17 11 10 12 element
PASS 3:
-3 5 17 11 10 12 Find the minumum
-3 5 17 11 10 12 exchange with 2nd
-3 5 10 11 17 12 element
pos = k;
for (j=k+1; j<size; j++)
if (x[j] < x[pos])
pos = j;
return pos;
}
Of the order of n2
PASS 1:
10 5 17 11 -3 12 item = 5
? 10 17 11 -3 12 compare 5 and 10
5 10 17 11 -3 12 insert 5
PASS 2:
5 10 17 11 -3 12 item = 17
5 10 17 11 -3 12 compare 17 and 10
PASS 3:
5 10 17 11 -3 12 item = 11
5 10 ? 17 -3 12 compare 11 and 17
5 10 ? 17 -3 12 compare 11 and 10
5 10 11 17 -3 12 insert 11
– Best case?
1 + 1 + … … to (n-1) terms = (n-1)
PASS 1:
10 5 17 11 -3 12
5 10 17 11 -3 12
5 10 17 11 -3 12
5 10 11 17 -3 12
5 10 11 -3 17 12
5 10 11 -3 12 17
PASS 2:
5 10 11 -3 12 17
5 10 11 -3 12 17
5 10 11 -3 12 17
5 10 -3 11 12 17
5 10 -3 11 12 17
• Number of comparisons :
– Worst case?
1 + 2 + 3 + … … + (n-1) = n(n-1)/2
– Best case?
Same