Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <limits.h>
- #define N (1 << 17)
- clock_t start, end;
- void print_time(void) {
- printf("CLOCKS_PER_SEC = %ld, start = %ld, end = %ld\n", CLOCKS_PER_SEC, start, end);
- printf("time = %lf\n\n", (double) (end - start) / CLOCKS_PER_SEC);
- }
- void selection_sort(double *v, int n) {
- int i, j, k;
- double min;
- for (i = 0; i < n - 1; i++) {
- min = v[i]; k = i;
- for (j = i + 1; j < n; j++) if (v[j] < min) { min = v[j]; k = j; }
- v[k] = v[i]; v[i] = min;
- }
- }
- void insertion_sort(double *v, int n) {
- int i, j;
- double t;
- for (i = 1; i < n; i++) {
- t = v[i];
- for (j = i - 1; j >= 0 && v[j] > t; j--) v[j + 1] = v[j];
- v[j + 1] = t;
- }
- }
- void init(double *v, int n) {
- int i;
- for (i = 0; i < N; i++) v[i] = (random() / (double) (RAND_MAX + 1.));
- }
- void print_first_five_elements(double *v) {
- printf("first 5 elements: %lf, %lf, %lf, %lf, %lf\n", v[0], v[1], v[2], v[3], v[4]);
- }
- int main(void) {
- int trial = 3;
- double v[N];
- srandom((unsigned) time(NULL));
- while (trial--) {
- init(v, N);
- puts("Selection Sort:");
- start = clock(); selection_sort(v, N); end = clock();
- print_first_five_elements(v);
- print_time();
- init(v, N);
- puts("Insertion Sort:");
- start = clock(); insertion_sort(v, N); end = clock();
- print_first_five_elements(v);
- print_time();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement