Đây là bài cấu trúc + 2 điểm của môn CTDL
Các bạn xem tham khảo:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void nhap(int a[],int n)
{
int i;
randomize();
for(i=0;i<n;i++)
a[i]=random(100);
}
void xuat(int a[],int n)
{
int i;
for(i=0;i<n;i++)
printf("%5d",a[i]);
}
void hoanvi(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void selectionsort(int a[],int n)
{
clrscr();
printf("\n\t\t\t CHUONG TRINH SAP XEP");
printf("\n\t\t\t\t LE THANH HAU");
printf("\n\t\t\t MSSV: 08101B0015");
printf("\n\n\t\tSELECTION SORT");
printf("\n\tCac phan tu truoc khi sap xep:");
printf("\n\n\t");
xuat(a,n);
int i,j,vtmin;
printf("\n\n\tQua trinh sap xep:");
for(i=0;i<n;i++)
{
vtmin=i;
for(j=i+1;j<n;j++)
if(a[vtmin]>a[j])
vtmin=j;
printf("\n\n\t");
xuat(a,n);
if(i!=vtmin)
hoanvi(a[i],a[vtmin]);
}
printf("\n\n\tCac phan tu sau khi sap xep:");
printf("\n\n\t");
xuat(a,n);
}
void insertionsort(int a[],int n)
{
clrscr();
printf("\n\t\t\t CHUONG TRINH SAP XEP");
printf("\n\t\t\t\t LE THANH HAU");
printf("\n\t\t\t MSSV: 08101B0015");
printf("\n\n\t\tINSERTION SORT");
printf("\n\tCac phan tu truoc khi sap xep:");
printf("\n\n\t");
xuat(a,n);
int x,i,pos;
printf("\n\n\tQua trinh sap xep:");
for(i=0;i<n;i++)
{
x=a[i];
pos=i-1;
while((pos>=0)&&(a[pos]>x))
{
a[pos+1]=a[pos];
pos --;
}
a[pos+1]=x;
printf("\n\n\t");
xuat(a,n);
}
printf("\n\n\tCac phan tu sau khi sap xep:");
printf("\n\n\t");
xuat(a,n);
}
void main()
{
int n,a[100],c;
char ch;
do
{
clrscr();
printf("\n\t\t\t CHUONG TRINH SAP XEP");
printf("\n\t\t\t\t LE THANH HAU");
printf("\n\t\t\t MSSV: 08101B0015");
printf("\n\n\tNhap so phan tu: ");
scanf("%d",&n);
nhap(a,n);
printf("\n\tCac phan tu truoc khi sap xep:");
printf("\n\n\t");
xuat(a,n);
printf("\n\n\n\tCAC PHUONG PHAP SAP XEP:");
printf("\n\t1: Phuong phap chon truc tiep (SelectionSort)");
printf("\n\t2: Phuong phap chen truc tiep (InsertionSort)");
printf("\n\t0: Thoat chuong trinh");
printf("\n\tBan chon chuc nang: ");
scanf("%d",&c);
switch(c)
{
case 1:
{
printf("\n\tPhuong phap chon truc tiep (SelectionSort)");
selectionsort(a,n);
break;
}
case 2:
{
printf("\n\tPhuong phap chen truc tiep (InsertionSort)");
insertionsort(a,n);
break;
}
}
printf("\n\n\tBan co muon quay lai khong (c/k)");
ch = getch();
}while((ch=='c')||(ch=='C'));
getch();
}