forked from ycshu/110_Fast_Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6_sorting.c
More file actions
91 lines (75 loc) · 1.56 KB
/
6_sorting.c
File metadata and controls
91 lines (75 loc) · 1.56 KB
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
88
89
90
91
#include <stdio.h> // for printf function
#include <stdlib.h> // for memory allocation
#include <time.h> // for time calculation
#include <math.h> // for sine and cosine functions
int main() {
// Declare all the variables
int k, m, n, N;
double *x, *y, z, p;
time_t t;
// Input the number N
printf("Input N: ");
scanf("%d",&N);
// Locate the memory for x and y;
x = (double *) malloc(N*sizeof(double));
y = (double *) malloc(N*sizeof(double));
// Initial setting for x, for example, x[k] = 1.0*rand()/RAND_MAX
srand( time(NULL) );
for(k=0;k<N;++k){
x[k] = y[k] = 1.0*rand()/RAND_MAX;
}
t = clock();
// sorting x;
for(n=0;n<N;++n) {
for(k=n+1;k<N;++k) {
if (x[n] > x[k]) {
z = x[n];
x[n] = x[k];
x[k] = z;
}
}
}
t = clock() - t;
// print y, x, and time
printf("Sorting %d elements: %f s\n", N, 1.0*t/CLOCKS_PER_SEC);
if(N<10) {
printf("y \t\t x\n");
for(k=0;k<N;++k) {
printf("%f\t%f\n",y[k],x[k]);
}
}
for(k=0;k<N;++k){
x[k] = y[k];
}
t = clock();
// put x[N-1] at the right location
p = x[N-1]; n = 0;
for(k=0;k<N-1;k++) {
// put all elements smaller than p from the beginning
if (x[k] < p) {
printf("swap %d <-> %d\n",k,n);
z = x[n];
x[n] = x[k];
x[k] = z;
n++;
}
}
z = x[n];
x[n] = x[N-1];
x[N-1] = z;
// x[0] is at the correct location!
if(N<10) {
printf("y \t\t x\n");
for(k=0;k<N;++k) {
printf("%f\t%f\n",y[k],x[k]);
}
}
// sorting
t = clock() - t;
// free the memory located by x, y
free(x);
free(y);
return 100;
}
int quick_sort(double *x, int L, int R){
}