Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лабораторная по МП 3,4.docx
Скачиваний:
3
Добавлен:
04.11.2018
Размер:
89.35 Кб
Скачать

Пример выполнения задания

Сравнить обменную поразрядную сортировку с сортировкой методом Шелла.

Программа

#include <stdio.h>

#include <conio.h>

#include <math.h>

#include <string.h>

#include <time.h>

clock_t start,end;

long comp,repl;

unsigned int a[4000],t[4000];

int shell[4]={8,4,2,1};

int n;

void sort1(int l,int r,int b)

{

if (l>=r) return;

int i=l,j=r,t;

while(i<j)

{

for(;i<j;i++) {comp++; if (((a[i]>>b)&1)==1) break;}

if (i==j) break;

for(;i<j;j--) {comp++;if (((a[j]>>b)&1)==0) break;}

if (i==j) break;

repl++;

t=a[i],a[i]=a[j],a[j]=t,i++,j--;

}

if (b==0) return;

if(((a[i]>>b)&1)==1)

{

sort1(l,i-1,b-1);

sort1(i,r,b-1);

}

else

{

sort1(l,i,b-1);

sort1(i+1,r,b-1);

}

}

void sort(int n)

{

for(int i=0;i<n-1;i++)

{

int k=i;

for(int j=i+1;j<n;j++,comp++)

if(t[k]>t[j]) k=j;

if (k!=i)

{

int r=t[k];

t[k]=t[i];

t[i]=r;

repl++;

}

}

}

void sort2 (void)

{

for(int i=0;i<4;i++)

{

int x=shell[i];

for(int j=0;j<x;j++)

{

int k=0,l=j;

while (l<n)

{

t[k]=a[j+k*x];

l+=shell[i];

k++;

}

sort (k);

for(l=0;l<k;l++) a[j+l*x]=t[l];

}

}

}

void main (void)

{

FILE *in,*out1,*out2;

if ((in=fopen("s:\\in.txt","r"))==NULL) return;

if ((out1=fopen("s:\\out1.txt","w"))==NULL) return;

if ((out2=fopen("s:\\out2.txt","w"))==NULL) return;

int i=0,r=0;

while(1)

{

if (feof(in)) break;

fscanf(in,"%d",&a[n]);

if(a[n]>i) i=a [n];

n++;

}

while(i) r++,i=i>>1;

start=clock();

sort1(0,n-1,r-1);

end=clock();

for(i=0;i<n;i++)

fprintf(out1,"%d\n",a[i]);

fprintf(out1,"Porazr Sort\n");

fprintf(out1,"Compares: %ld\nSwitches: %ld\n",comp,repl);

fprintf(out1,"Time: %f",(end-start)/CLK_TCK);

fclose(out1);

n=0,comp=0,repl=0;

fseek(in,0,0);

while(1)

{

if (feof(in)) break;

fscanf(in,"%d",&a[n]);

n++;

}

fclose(in);

start=clock();

sort2();

end=clock();

for(i=0;i<n;i++)

fprintf(out2,"%d\n",a[i]);

fprintf(out2,"Shell Sort\n");

fprintf(out2,"Compares: %ld\nSwitches: %ld\n",comp,repl);

fprintf(out2,"Time: %f",(end-start)/CLK_TCK);

fclose(out2);

}

Результаты работы программы

  1. Входные данные:

1 23 45 654 56 354 65 565 65 2 64 897 999 654 123 98 8

  1. Обменная поразрядная сортировка:

1

2

8

23

45

56

64

65

65

98

123

354

565

654

654

897

999

Porazr Sort

Compares: 101

Switches: 15

Time: 0.000000

  1. Сортировка Шелла:

1

2

8

23

45

56

64

65

65

98

123

354

565

654

654

897

999

Shell Sort

Compares: 238

Switches: 21

Time: 0.000000