You are on page 1of 3

I.

Thut ton sp xp

THUT TON SP XP & TM KIM

1. Selection Sort
Code:
void selectionsort(int a[], int n)
{
int m, i, j;
for(i=0;i<n-1;i++)
{
m=i;
for(j=i+1;j<n;j++)
if(a[j]<a[m]) //tng dn a[j]<a[m], gim dn a[j]>a[m]
m=j;
if(m!=i)
swap(a[m],a[i]);
}
}
2. Insertion Sort
Code:
void insertionsort(int a[], int n)
{
int i,x,pos;
for(i=0;i<n;i++)
{
x=a[i];
for(pos=i;pos>0&& a[pos-1]>x;pos--) //tng dn a[pos-1]>x, gim dn a[pos-1]<x
a[pos]=a[pos-1];
a[pos]=x;
}
}
3. Binary Insertion Sort
Code:
void binsertionsort(int a[], int n)
{
int i,j,l,r,m,x;
for(i=1;i<n;i++)
{
x=a[i];
l=0; r=i-1;
while(l<=r)
{
m=(l+r)/2;
if(x<a[m]) //tng dn x<a[m], gim dn x>a[m]
r=m-1;
else
l=m+1;
}
for(j=i;j>l;j--)
a[j]=a[j-1];
a[l]=x;
}
}

4. Interchange Sort
Code:
void interchangesort(int a[], int n)
{
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j]) //tng dn a[i]>a[j], gim dn a[i]<a[j]
swap(a[i],a[j]);
}
5. Buble Sort
Code:
void bublesort(int a[],int n)//Chuong trinh sap xep bang Buble Sort
{
int i,j
for(int i=0;i<n-1;i++)
for(int j=n-1;j>i;j--)
if(a[j]<a[j-1])//tng dn a[j]<a[j-1], gim dn a[j]>a[j-1]
swap(a[j-1],a[j]);
}
6. Shaker Sort
Code:
void shakersort(int a[],int n)
{
int l,r,j;
l=0;r=n-1;
while(l<r)
{
for(j=r;j>l;j--)
if(a[j]<a[j-1])//tng dn a[j]<a[j-1], gim dn a[j]>a[j-1]
swap(a[j],a[j-1]);
l++;
for(j=l;j<r;j++)
if(a[j]>a[j+1])//tng dn a[j]>a[j+1], gim dn a[j]<a[j+1]
swap(a[j],a[j+1]);
r--;
}
}
7. Hm hon v
Code: (phi c t trc cc hm sp xp hoc khai bo prototype)
void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}

II. Tm kim
1. Tm kim tun t (c th tm nhiu i tng tha iu kin)
Code:
void timkiemtuantu(int a[],int n,int x)
{
int i,thay=-1;
for(i=0;i<n;i++)
if(a[i]==x)
{
thay=i;
break; //dng cu lnh in ra gi tr i tm tt c cc i tng tha iu kin
}
if(thay<0)
cout<<Khong tim thay giai tri <<x<< trong mang!;
else //khng cn else nu tm tt c cc i tng
cout<<Tim thay gia tri <<x<< tai vi tri:<<thay+1;
}
2.Tm kim nh phn (ch kim c nu mng c sp xp v khng c d liu trng)
Code:
void timkiemnhiphan(int a[],int n,int x)
{
int l,r,m,i,OK=0;
l=0;
r=n-1;
while(l<=r)
{
m=(l+r)/2;
if(x<a[m]) //x<a[m] d liu sp xp tng, x>a[m] d liu sp xp gim
r=m-1;
else
if(x>a[m]) //x>a[m] d liu sp xp tng, x<a[m] d liu sp xp gim
l=m+1;
else
{
OK=1;
cout<<Tim thay gia tri <<x<< tai vi tri: <<m+1;
return;
}
}
if(!OK)
cout<<Khong tim thay gia tri <<x<< trong mang!;
}

You might also like