Problem 22 solution
More...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
◆ MAX_NAME_LEN
Maximum length of each name
◆ MAX_NAMES
Maximum number of names to store
◆ lazy_sort()
void lazy_sort |
( |
char |
data[][MAX_NAME_LEN], |
|
|
int |
LEN |
|
) |
| |
Alphabetical sorting using 'lazy sort' algorithm
52 for (i = 0; i < LEN; i++)
54 for (j = i + 1; j < LEN; j++)
59 strcpy(tmp_buffer,
data[i]);
61 strcpy(
data[j], tmp_buffer);
66 for (i = 0; i < LEN; i++)
67 printf(
"%s\t",
data[i]);
◆ main()
int main |
( |
int |
argc, |
|
|
char ** |
argv |
|
) |
| |
Main function
74 unsigned long COUNT = 0;
75 char *fname =
"names.txt";
80 method = atoi(argv[1]);
82 FILE *fp = fopen(fname,
"rt");
85 perror(
"Unable to open file");
94 int ret = fscanf(fp,
"\"%[^\",]\",", names[COUNT++]);
101 printf(
"\nTotal number of names: %lu\n", COUNT);
105 clock_t start_time = clock();
107 clock_t end_time = clock();
108 printf(
"\nShell sort: %.4g millisecond\n",
109 1e3 * (end_time - start_time) / CLOCKS_PER_SEC);
111 else if (method == 1)
113 clock_t start_time = clock();
115 clock_t end_time = clock();
116 printf(
"\nLazy sort: %.4g millisecond\n",
117 1e3 * (end_time - start_time) / CLOCKS_PER_SEC);
121 clock_t start_time = clock();
125 #pragma omp parallel for schedule(runtime) reduction(+ : sum_score)
128 for (i = 935; i < 940; i++)
130 for (i = 0; i < COUNT; i++)
133 unsigned int score = 0;
135 for (
int j = 0; names[i][j] !=
'\0'; j++)
136 score += names[i][j] -
'A' +
138 sum_score += score * (i + 1);
140 printf(
"Name: %s\tScore: %u x %u = %lu\n", names[i], score, i + 1,
141 (
unsigned long)score * (i + 1));
144 clock_t end_time = clock();
145 printf(
"Scoring time: %.4g millisecond\n",
146 1e3 * (end_time - start_time) / CLOCKS_PER_SEC);
148 printf(
"Total Score = %lu\n", sum_score);
◆ shell_sort()
void shell_sort |
( |
char |
data[][MAX_NAME_LEN], |
|
|
int |
LEN |
|
) |
| |
Alphabetical sorting using 'shell sort' algorithm
22 const int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1};
23 const int gap_len = 8;
26 for (g = 0; g < gap_len; g++)
29 for (i = gap; i < LEN; i++)
32 strcpy(tmp_buffer,
data[i]);
34 for (j = i; j >= gap && strcmp(
data[j - gap], tmp_buffer) > 0;
37 strcpy(
data[j], tmp_buffer);
41 for (i = 0; i < LEN; i++)
42 printf(
"%s\t",
data[i]);