vulogo0207 Chief Petty Officer
Tổng số bài gửi : 56 Points : 106 Danh Vọng : 2 Join date : 29/06/2009 Age : 35
| Tiêu đề: Cấu trúc dữ liệu và giải thuật II: Sắp xếp Sat Jul 11, 2009 11:32 am | |
| Insertion Sort - Code:
-
#include"stdio.h" #define max 100 void nhapmang(int &n,int a[]) { printf("Moi ban nhap so phan tu n:"); scanf("%d",&n); for(int i=0;i<n;i++) { printf("a[%d]= ",i); scanf("%d",&a[i]); } } void xuatmang(int n,int a[]) { for(int i=0;i<n;i++) { printf("%d ",a[i]); } printf("\n"); } void Insertion(int n,int a[]) { int temp; int pos; for(int i=0;i<n;i++) { temp=a[i]; pos=i-1; while(pos>=0&&temp<a[pos]) { a[pos+1]=a[pos]; pos--; } a[pos+1]=temp; xuatmang(n,a); } } void main() { int n; int a[max]; nhapmang(n,a); Insertion(n,a); }
| |
|
vulogo0207 Chief Petty Officer
Tổng số bài gửi : 56 Points : 106 Danh Vọng : 2 Join date : 29/06/2009 Age : 35
| Tiêu đề: Re: Cấu trúc dữ liệu và giải thuật II: Sắp xếp Sun Jul 12, 2009 12:07 pm | |
| Shell sortShell sort cũng tương tự Insertion sort chỉ có những điểm khác sau 1) Thay vì bước nhảy là 1 thì bước nhảy sẽ là k 2) Biến k sẽ được điều khiển bẳng vòng while 3) Những chỗ +1 hoặc - 1 sẽ được thay bẳng k - Code:
-
#include "stdio.h" #define max 100 void nhapmang(int &n, int a[]) { printf("Moi nhap so phan tu n:"); scanf("%d",&n); for(int i=0;i<n;i++) { printf("a[%d]=",i); scanf("%d",&a[i]); } } void xuatmang(int n,int a[]) { for(int i=0;i<n;i++) { printf("%d ",a[i]); } } void Shell(int n, int a[]) { int k=n/2; //thêm biến bước nhảy k int pos; int temp; while(k!=0) //vòng lặp điều khiển bước nhảy k { for(int i=k;i<n;i+=k) //thay 1 bằng k { temp=a[i]; pos=i-k; //thay 1 bằng k while(pos>=0&&a[pos]>temp) { a[pos+k]=a[pos]; //thay 1 bằng k pos-=k; } a[pos+k]=temp; //thay 1 bằng k } k=k/2; } } void main() { int n; int a[max]; nhapmang(n,a); printf("Mang sau khi nhap: "); xuatmang(n,a); printf("\n"); Shell(n,a); xuatmang(n,a); printf("\n"); } | |
|