al_hw1.cpp
2.61 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cmath>
using namespace std;
// sorting algorithms
void mergeSort(int n, int s[]);
void merge(int h,int m, int u[], int v[], int s[]);
void exchangeSort(int n, int s[]);
// time checking algorithms
double cpu_time ( void );
void functionTimeCheck(string sort_type, int s[], int sLength);
int main() {
cout << "Problem Scale : ";
int input; // user input
cin >> input;
// create arrays
int s_merge[input];
int s_ex[input];
// create random numbers to arrays
srand(time(NULL));
for(int i=0; i<input; i++){
int rnum = rand()%1000;
s_merge[i] = rnum;
s_ex[i] = rnum;
}
// time check - merge sort
functionTimeCheck("merge",s_merge, input);
// print sorted values
/*
cout << "merge sort : [";
for(int i=0; i<input; i++){
if(i==(input-1))
cout << s_merge[i] << "]" << endl;
else
cout << s_merge[i] << ", ";
}
*/
// time check - excahnge sort
functionTimeCheck("exchange",s_ex, input);
// print sorted values
/*
cout << "exchange sort : [";
for(int i=0; i<input; i++){
if(i==(input-1))
cout << s_ex[i] << "]" << endl;
else
cout << s_ex[i] << ", ";
}
*/
return 0;
}
// Merge Sort
void mergeSort(int n, int s[]){
int h = n/2;
int m = n-h;
if(n>1) {
int leftHalf[h];
int rightHalf[m];
for(int i=0;i<h;i++)
leftHalf[i] = s[i];
for(int i=0;i<m;i++)
rightHalf[i] = s[h+i];
mergeSort(h,leftHalf);
mergeSort(m,rightHalf);
merge(h,m,leftHalf,rightHalf,s);
}
}
// merge
void merge(int h,int m, int u[], int v[], int s[]){
int i=0; int j=0; int k=0;
while(i<=h-1 and j<=m-1){
if(u[i]<v[j]){
s[k]=u[i];
i+=1;
}
else{
s[k]=v[j];
j+=1;
}
k+=1;
}
if(i>h-1){
for(int ii=j; ii<m; ii++){
s[k]=v[ii];
k += 1;
}
}
else{
for(int ii=i; ii<h; ii++){
s[k]=u[ii];
k += 1;
}
}
}
// Exchange Sort
void exchangeSort(int n, int s[]){
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
if(s[i] > s[j]){
int temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
}
double cpu_time ( ) {
double value;
value = ( double ) clock ( ) / ( double ) CLOCKS_PER_SEC;
return value;
}
// time check and print
void functionTimeCheck(string sort_type, int s[], int sLength){
double atime, btime;
if(sort_type == "merge"){
atime = cpu_time();
mergeSort(sLength,s);
btime = cpu_time();
cout << "merge sort : " << -atime + btime << endl;
}
else if(sort_type == "exchange"){
atime = cpu_time();
exchangeSort(sLength,s);
btime = cpu_time();
cout << "exchange sort : " << -atime + btime << endl;
}
}