Professional Documents
Culture Documents
u.cs101 - Алгоритм Программчлал-13 m
u.cs101 - Алгоритм Программчлал-13 m
13
, -
www.emust.edu.mn
:
01
01
02
02
03
04
, -
www.emust.edu.mn
, -
.
, .
: 1 , 2 , n :
1 , 2 , n .
.
.
.
, -
.
.
( ) .
.
.
( )
( )
.
, -
. .
,
,
.
.
.
, -
.
.
. N
N2 N
.
. (
) N
.
, -
.
,
,
.
selectionSort () .
template<class Type> void selectionSort(Type a[], int n) (
int i, j, min;
, -
selectionSort ( )
. int char
. int a [ 8 ] = { 77, 33, 44, 11, 88, 22, 66, 55 } ;
char s [ 15 ] = {a , b, o , r, t, n ,
g, e, x, a, m, p, l, e} ;
selectionSort ( a, 8) ;
selectionSort ( s, 15) ;
.
, -
n2 , n
. i
n-1 .
( n )
( n ) = (n-1) + (n-2) +.+ 2 + 1 = n(n-1)/2 = O (n2)
.
NM
N2 NM . N=O(M)
.
, -
,
.
.
.
InsertionSort ( ) .
, -
template<class Type>
void insertitionSort (Type a [ ] , int I , int n ) {
for (int I = 1 ; I < n; I ++) {
Type element = a [ I ] ;
Int j = I 1 ;
While ( j >= 0 && element < a [ j ] )
a [ j+1 ] = a [ j] ;
a [ j+1 ] = element ;
}
}
, -
I
.
. ,
. while
.
, -
( )
.
j
( ) .
while j>=0
. j
.
(
) .
, -
.
while ( element <a[ j ] )
.
. f ( n
)
.
.
, -
k
k-1 . f(n)
= 1 + 2 + 3 + + (n-1) / 2 O(n2)
.
.
(k-1) /2
f(n) = + 2/2 + 3/2 + + (n-1) /2 = n(n-1) / 4 = O(n2)
.
, -
.
1- 2
. N .
, -
.
.
.
.
bubbleSort ( ) .
, -
, -
i-
.
.
f(n) = (n-1) + (n-2) + . + 2 + 1 = (n-1)/2 = O(n2)
.
.
O(n2) .
, -
.
.
Template<class Type>
Void bubbleSort (Type a [] , iny n ) {
bool sorted = false ;
for (int i=n-1; I >o && !sorted ; I ++ ) {
sorted = true ;
for (int j = 0 ; j <1 ; j ++)
, -
sorted
.
.
(n-1) + (n-2) + .+ (n-ksorted ) * (2n ksorted -1 ) /2
, -
ksorted
.
!sorted
.
ksorted
.
.
.
.
.
, -
Shell-
( D . L . Shell )
.
,
.
N
. shell-
.
, -
h h
h
.
o , h, 2h _ ,
1, h+1, 2h+1 _
i=0,1,, h-1 i, (i+h), (i+2h),
h .
h- 1-
. h
.
h-
.
h-
.
, -
t=a[I];j=I;
While (j >=h && t < a [ j-h ]
a [ j ] = a [ j-h ] ;
j -=h ;
}
a[j]=t;
}
}
h N-
.
, -
h
.
Shell- N3/2
. O(N1.25 )
O(N1.5 ) .
, -
Figure 8-12
Selection sort
Figure 8-14
Selection sort
algorithm
Figure 8-15
Bubble sort
Figure 8-17
Insertion sort
Figure 8-19
Search concept
Figure 8-21