Anda di halaman 1dari 5

unsigned int

factoriel( unsigned int n )


{
if( n <= 1 ) return 1;
else
return( n * factoriel(n-1) );
}
T(1)=c
T(n)=d+T(n-1)
T(n-1)=T(n-2)+d
T(n-2)=T(n-3)+d
.
T(n)=T(n-1)+d=T(n-2)+2d=T(n-3)+3d=.=T(n-i)+id
n-i=1 T(1)=c i=n-1
T(n)=T(1)+(n-1)d=c-d+dn
O(n)
quicksort

T(1)=c n1
T(n)=2T(n/2)+dn

T(n/2)=2T(n/4)+dn/2
T(n/4)=2T(n/8)+dn/4
..
T(n)=2T(n/2)+dn=4T(n/4)+2dn=8T(n/8)+3dn==2iT(n/2i)+idn
n/2i=1 i=log n
T(n)=2log n T(1)+dn log n=cn + dn log n
2log n=n
quicksort O(n log n)
A
T(1)=c
T(n)=d+T(n/2)

T(n/2)=T(n/4)+d
T(n/4)=T(n/8)+d
.
T(n)=T(n/2)+d=T(n/4)+2d=T(n/8)+3d=.=T(n/2i)+id
n/2i =1 T(1)=c i=log n
T(n)=T(1)+ d log n=c+d log n
O(log n)

64
3 .

.
?
T(64)=264-1=1,84 x 1019
3 1 2

.
: .
1.
.
2.
.
n 1
2 3 :
1. n-1 1 3,
1 .
2. 1 2.
3. n-1 3 2.
T(n) n 1
2.

Heap
# include <iostream>
# include <alloc>
typedef int ElementType ;
void siftdown(ElementType array[], int lower, int upper)
{
int i = lower, c = lower, lastindex = upper/2; ElementType temp;
temp = array[i];
while (c < lastindex) {
c = 2 * i + 1;
if (c + 1 < upper && (array[c + 1] > array[c]))
c++;
if (temp >= array[c]) break;
array[i] = array[c];
i = c;
}
array[i] = temp;
}
void heapsort (ElementType array[], int len)
{
int i,a; ElementType temp;
for (i = (len / 2)-1; i >= 0; i--)
siftdown (array, i, len);
for (i = len-1; i >= 1; i--) {
temp=array[0];
array[0]=array[i];
3

array[i]=temp;
siftdown (array, 0, i );
}
}
void main()
{ int i, n=11;
int niza[11]={15,6,18,3,2,4,7,13,9,17,2};
heapsort (niza, n);
for (i=0; i<n; i++)
cout<<niza[i] <<" ";
}
(Merge Sort)
# include <iostream>
# include <alloc>
typedef int ElementType ;
void merge(ElementType a[], ElementType temp[], int left, int mid, int right)
{
int i = left, j = mid, k = left;
while (i < mid && j <= right){
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i < mid)
temp[k++] = a[i++];
while (j <= right)
temp[k++] = a[j++];
for(i = left; i <=right; ++i)
a[i] = temp[i];
}
void MSort(ElementType a[], ElementType temp[], int left, int right){
int mid;
if (right>left)
{
mid = (right + left)/2;
MSort(a, temp, left, mid);
MSort(a, temp, mid+1, right);
merge(a, temp, left, mid+1, right);
}
}
void Mergesort( ElementType A[ ], int N )
{
4

ElementType *TmpArray;
TmpArray = (ElementType *)malloc(N * sizeof( ElementType ) );
if( TmpArray != NULL ){
MSort( A, TmpArray, 0, N - 1 );
free( TmpArray );
}
else
cout << "Nema prostor za poleto tmp!!!";
}
main()
{ int i, n=11;
int niza[11]={15,6,18,3,2,4,7,13,9,17,2};
Mergesort (niza, n);
for (i=0; i<n; i++)
cout<<niza[i] <<" ";
return 0;
}

T(1)=c n1
T(n)=2T(n/2)+dn
T(n/2)=2T(n/4)+dn/2
T(n/4)=2T(n/8)+dn/4
..
T(n)=2T(n/2)+dn=4T(n/4)+2dn=8T(n/8)+3dn==2iT(n/2i)+idn
n/2i=1 i=log n
T(n)=2log n T(1)+dn log n=cn + dn log n
2log n=n
O(n log n)

Anda mungkin juga menyukai