L10 SortSearch
L10 SortSearch
• Basic idea:
– Start at the beginning of the array.
– Inspect elements one by one to see if it matches the key.
• Time complexity:
– A measure of how long an algorithm takes to run.
– If there are n elements in the array:
• Best case:
match found in first element (1 search operation)
• Worst case:
no match found, or match found in the last element
(n search operations)
• Average case:
(n + 1) / 2 search operations
Returns -1
• What we want?
– Find split between values larger and smaller than key:
0 n-1
x: <=key >key
L R
Sorted array
-17 -5 3 6 12 21 45 63 50
L= –1; R= 9; x[4]=12;
Trace :
L= –1; R=4; x[1]= –5;
binsearch (x, 9, 3); L= 1; R=4; x[2]=3;
L=2; R=4; x[3]=6;
binsearch (x, 9, 145); L=2; R=3; return L;
• Original list:
10, 30, 20, 80, 70, 10, 60, 40, 70
• What we want ?
– Data sorted in 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.
0 k mval size-1
swap
Spring Semester 2007 Programming and Data Structure 23
Subproblem
pos = k;
for (j=k+1; j<size; j++)
if (x[j] < x[pos])
pos = j;
return pos;
}
x: 3 12 -5 6 142 21 -17 45
x: -17 -5 3 6 12 21 142 45
x: -17 12 -5 6 142 21 3 45
x: -17 -5 3 6 12 21 142 45
x: -17 -5 12 6 142 21 3 45
x: -17 -5 3 6 12 21 45 142
x: -17 -5 3 6 142 21 12 45
x: -17 -5 3 6 142 21 12 45
Of the order of n2
• General situation :
0 i size-1
x: sorted remainder, unsorted
i Compare and
shift till x[i] is
larger.
i
0 j size-1
– Best case?
1 + 1 + …… to (n-1) terms = (n-1)
• Number of comparisons :
– Worst case?
1 + 2 + 3 + …… + (n-1) = n(n-1)/2
– Best case?
Same
0 size-1
x:
pivot
Perform Perform
partitioning partitioning
26 33 35 29 19 12 22
22 35 29 19 12 33
22 12 29 19 35 33 The partitioning
22 12 19 29 35 33 process
19 22 12 26 29 35 33
45 -56 78 90 -3 -6 123 0 -3 45 69 68
-6 -56 -3 0 -3 45 123 90 78 45 69 68
-56 -6 -3 0 -3 68 90 78 45 69 123
-3 0 -3 45 68 78 90 69
-3 0 69 78 90
• Worst case:
n2 ==> list is already sorted
• Average case:
n log2n
Input Array
Part-I Part-II
Merge Split
Sorted Arrays
0 m 0 n
0 m+n-1
if (n>1) {
k = n/2; m = n-k;
b = (int *) calloc(k,sizeof(int));
c = (int *) calloc(m,sizeof(int));
for (i=0; i<k; i++)
b[i]=a[i];
for (j=k; j<n; j++)
c[j-l]=a[j];
for (i=0;i<12;i++)
printf ("%d ",a[i]);
printf ("\n");