Professional Documents
Culture Documents
Algorithm Lec 12
Algorithm Lec 12
-13
: . //
.
.
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;
for (i=0; i<n-1; i++) ( min = i;
for ( j = i+1 ; j<n ; j++ )
if ( a [ j ] < a [ min ] ) min = j ;
swap ( a , I , min ) ;
Selection ( ) . i
. J
I
swap ()
. i
.
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
1. U.CS101 13
2. http://flowgorithm.org/documentation flowgorithm