0% found this document useful (0 votes)
12 views3 pages

Insertion Sort

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views3 pages

Insertion Sort

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

******SHOW TỪNG VÒNG : *********

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void initializeA(int a[], int n, int min, int max) {


for (int i=0; i<n; i++) {
a[i]= min + rand() % (max - min +1);
}
}

void insertionSort(int a[], int n, int *comps, int *shifts, int *c, int *s) {
(*c)=0;
(*s)=0;
for (int i=1; i<n; i++) {
(*comps) = 0;
(*shifts) = 0;
int key = a[i];
int j = i-1;
while (j >=0 && key < a[j]) {
(*comps)++;
(*c)++;
(*shifts)++;
(*s)++;
a[j+1] = a[j];
j--;
}
(*comps)++; /dừng while nghĩa là them 1 lần so sánh/
(*c)++;
a[j+1] = key;
printf("Vong %d: ", i);
for(int k=0; k<n; k++) {
printf("%d ", a[k]);
}
printf("\n");
printf("Comps = %d ; Shifts = %d\n\n", *comps, *shifts);
}
}

int main() {
time_t t;
srand((unsigned) time(&t));
int a[10];
int n=10;
int comps, shifts, c,s;
initializeA(a,n,-100,100);
for(int k=0; k<n; k++) {
printf("%d ", a[k]);
}
printf("\n");
insertionSort(a,n,&comps,&shifts,&c,&s);
printf("Total Comps = %d ; Shifts = %d\n", c,s);
return -1;
}

**********BẢNG*************

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void initializeA(int a[], int n, int min, int max) {


for (int i=0; i<n; i++) {
a[i]= min + rand() % (max - min +1);
}
}

double ave(int fre[], int n, int k) {


int sum =0;
for(int i=0; i<n; i++) {
sum+= fre[i]*i;
}
return (float)sum/k;
}

void insertionSort(int a[], int n, int *c, int *s) {


(*c)=0;
(*s)=0;
for (int i=1; i<n; i++) {
int key = a[i];
int j = i-1;
(*c)++;
while (j >=0 && key < a[j]) {
(*c)++;
a[j+1] = a[j];
(*s)++;
j--;
}
a[j+1] = key;
}
}

int main() {
time_t t;
srand((unsigned) time(&t));
int a[10];
int n=10;
int c,s;
int k[5] = {10,20,100,1000,10000};
for(int i=0; i<5; i++) {
printf("n = %d\n", k[i]);
int fre_c[200] = {0};
int fre_s[200] = {0};
for (int j= 0; j<k[i]; j++) {
initializeA(a,n,-100,100);
insertionSort(a,n,&c,&s);
fre_c[c]++;
fre_s[s]++;
}
float a1 = ave(fre_c, n*n, k[i]);
float a2 = ave(fre_s, n*n, k[i]);
printf(" Comps Shifts\n");
for (int k=0; k<n*n; k++) {
if (fre_c[k] > 0 || fre_s[k] > 0) {
printf("%d %d %d\n", k, fre_c[k], fre_s[k]);
}
}
printf("Average: %.3f %.3f\n", a1, a2);
}
return -1;
}

You might also like