Expected Behavior of Algorithms Linear Search

Θ
! "
#
$ "
$
$
% &
%#& ' Σ∀ % ⋅ % &&
template <class otype>
int location_by_linear_search
(const otype a[], const otype
&target, int n)
{
int i=0;
while (i<n && a[i] != target)
++i;
return i;
}
1
(
$
$
%)& * % & * % &
(
!
"
+
,)
.
-
/
.Θ% &
#
0
+*
1%#' & ' )2
* ,)
#
%#& ' Σ ⋅ 1%#' & '
+⋅)2 3 )⋅
)⋅)23 3% ,)&
)&⋅⋅)2 ' % ,)& 2
4
%#& ' Θ% &
5 ' Θ%#& $
%5&' Θ% &
2
template <class otype>
void simple_bubble_sort (otype a[], int n)
{
for (int k = n; k > 1; ---k)
k)
for (int j = 1; j <= k; ++j)
if (a[j] > a[j+1]])
swap (a[j], a[j+1]);
}
% ,)&2
4
6
-
/ 5
7
$
/
$
.
.
$
$
/
/
%5&' %/)&3 %/4&3 3 %/ &
"
8
+ )
,)9
!
$
)2
%/ & ' +23)23423 3% ,)&2' % ,)&2
4
%5&'%),
%),)&2
43%4,
%4,)&2
43 3% ,)&2
4
' % ,)&2
3
void binary_search (otype a[], otype &target,
int first, int last, bool & found, int &
subscript)
{
int mid;
found = false;
while (first <= last && !found) {
mid = (first + last)/2;
if (target < a[mid])
last = mid - 1;
else if (a[mid] < target)
first = mid + 1;
else
found = true;
}
if (found)
subscript = mid;
else
subscript = first;
}
(
$
$
)+
/ #
.
5
$
$
'+
':
4
% &
)
4
;
)2
)+ 42
)+ 2
)+ ;2
)+
%#& ' )%)2
)+& 3 4%42
)+& 3 ;% 2
)+& 3 %;2
)+& '
4:2
)+ ' 4 :
% &
4
)2
)+
;
<
=
>
)2
)+ 42
)+ 42
)+ )2
)+ 42
)+ )2
)+
%5& ' 4%)2
)+& 3 ;%)2
)+& 3 %42
)+& 3 %42
)+& 3
<%)2
)+& 3 =%42
)+& 3 >%)2
)+& ' )2
)+ ' )
5
;
% &
2
)) <2
))
%#& ' ;% 2
))& 3 %<2
))& ' ;:2
)) ≅ ;
% &
;
<
=
>
)2
)) ;2
)) )2
)) 42
)) ;2
)) )2
))
%5& ' ;%)2
))& 3 %;2
))& 3 %)2
))& 3 <%42
))& 3
=%;2
))& 3 >%)2
))& ' <)2
)) ≅
!
(
$
!
?
@
"
)
* A B
@
C A B
@
4 @
'' A B
@
; @
1% ;& ' )2
1% )& ' )2 % ,)&2
4
1% 4& ' )2 % ,)&2
4 ')2
2
4
6
!
/
#
6
# ') 3?
% 4∪ ;& 3 D
$
?
% 4∪ ;& )
D
4
;
%# & ' )31% 4∪ ;& 3 %D &
')31% 4∪ ;&31% )& %D E)& 3
1% 4& %D E4& 31% ;& %D E;&
"
"
%# & ' ) 3 )2 % 2
4 3)& 3
)2 % ,)&2
4 %# % ,)&24 & 3
)2 2
4 %# 24 & 3 +
?$
0% &' %# &
0% &' 3 2
4 3)30% % ,)&2
4 &30% 2
4&
0% & ' ;2
4
'C #
$ % & '()
7
*
/
+
#
! "
#+'+ #)'+
# ' 3)3 5 3 D $
5 '
D '
#
$%
7
# ' 3) 3 5 3 D
%# & ' 3) 3 %5 &3 %D &
5
D
/
"
"
+ * " * ,)
%5 & ' 1% +& %5 E+& 3 1% )& %5 E)& 3
3 1% ,)& %5 E ,)&
8
1% "& ' )2
%5 E"& ' %#"&
%5 & ' )2 A%#4&3 %#;&3 3 %# ,)&B
(
%D &
%# & ' 3)3 42 % %#4&3 %#;&3 3 %# ,)&&
F
0% & ' %# &
0% & ' 43 34A
0%4&30%;&3 30% ,)&B
0% & G % ,)& 0% ,)& $
0% &,
&,% ,)&0% ,)&' 4,% ,)&43 ,% ,)&340% ,)&
0% & ' % 3 )& 0% , )& 3 4
(
H% & ' 0% &2
% 3)& $
0% & ' %# & ≅ 4
≅ ) ;:
9