-
Notifications
You must be signed in to change notification settings - Fork 0
/
seqsort.c
87 lines (70 loc) · 2.06 KB
/
seqsort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// COMP3230 Programming Assignment Two
// The sequential version of the sorting using qsort
/*
# Filename:
# Student name and No.:
# Development platform:
# Remark:
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/time.h>
int checking(unsigned int *, long);
int compare(const void *, const void *);
// global variables
long size; // size of the array
unsigned int * intarr; // array of random integers
int main (int argc, char **argv)
{
long i, j;
struct timeval start, end;
if ((argc != 2))
{
printf("Usage: seq_sort <number>\n");
exit(0);
}
size = atol(argv[1]);
intarr = (unsigned int *)malloc(size*sizeof(unsigned int));
if (intarr == NULL) {perror("malloc"); exit(0); }
// set the random seed for generating a fixed random
// sequence across different runs
char * env = getenv("RANNUM"); //get the env variable
if (!env) //if not exists
srandom(3230);
else
srandom(atol(env));
for (i=0; i<size; i++) {
intarr[i] = random();
}
// measure the start time
gettimeofday(&start, NULL);
// just call the qsort library
// replace qsort by your parallel sorting algorithm using pthread
qsort(intarr, size, sizeof(unsigned int), compare);
// measure the end time
gettimeofday(&end, NULL);
if (!checking(intarr, size)) {
printf("The array is not in sorted order!!\n");
}
printf("Total elapsed time: %.4f s\n", (end.tv_sec - start.tv_sec)*1.0 + (end.tv_usec - start.tv_usec)/1000000.0);
free(intarr);
return 0;
}
int compare(const void * a, const void * b) {
return (*(unsigned int *)a>*(unsigned int *)b) ? 1 : ((*(unsigned int *)a==*(unsigned int *)b) ? 0 : -1);
}
int checking(unsigned int * list, long size) {
long i;
printf("First : %d\n", list[0]);
printf("At 25%%: %d\n", list[size/4]);
printf("At 50%%: %d\n", list[size/2]);
printf("At 75%%: %d\n", list[3*size/4]);
printf("Last : %d\n", list[size-1]);
for (i=0; i<size-1; i++) {
if (list[i] > list[i+1]) {
return 0;
}
}
return 1;
}