-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek_2_selection_mergesort.cpp
More file actions
148 lines (125 loc) · 2.71 KB
/
Copy pathweek_2_selection_mergesort.cpp
File metadata and controls
148 lines (125 loc) · 2.71 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
//
// ALGORITH.cpp
// exercise
//
// Created by Nurjol Badyelkhan on 2021/03/10.
//
#include <iostream>
#include<ctime>
using namespace std;
void selectionSort(int a[],int n){
for(int i=0;i<n;i++){
int idx = i;
for(int j=i+1;j<n;j++){
if (a[idx] > a[j]){
idx = j;
}
}
int temp = a[idx];
a[idx]=a[i];
a[i]= temp;
}
}
void merge(int a[], int l ,int m,int r)
{
int i = l;
int j = m+1;
int k = l;
int temp[100000];
while(i<=m && j<=r)
{
if(a[i]<=a[j]){
temp[k] = a[i];
i++;
k++;
}
else{
temp[k] = a[j];
j++;
k++;
}
}
while(i<=m)
{
temp[k] = a[i];
i++;
k++;
}
while(j<=r)
{
temp[k] = a[j];
j++;
k++;
}
for(int w= l; w<=r; w++)
{
a[w] = temp[w];
}
}
void mergeSort(int a[], int l ,int r){
if (r>l){
int m = (r+l)/2;
mergeSort(a, l, m);
mergeSort(a, m+1, r);
merge(a, l, m, r);
}
}
void checkSort(int a[],int n){
bool sorted;
sorted = true;
for(int i = 1 ; i<n;i++){
if (a[i-1]>a[i]){
sorted = false;
cout<<i-1<<" "<<i<<endl;
}
if(!sorted){
break;
}
}
if (sorted){
cout<<"sorting complete"<<endl;
}
else {
cout<<"Error during sorting..."<<endl;
}
}
int main(){
int array[10] = {6,2,8,1,3,9,4,5,10,7} ;
selectionSort(array, 10);
cout<<"1st question answer: after sorting with selection sort : "<<endl;
for(int i=0;i<10;i++){
cout<<array[i]<<" ";
}
cout<<endl;
int array1[10] = {6,2,8,1,3,9,4,5,10,7} ;
mergeSort(array1,0,9);
cout<<"2nd question answer: after sorting with merge sort : "<<endl;
for(int i=0;i<10;i++){
cout<<array1[i]<<" ";
}
cout<<endl;
int a[100000],b[100000];
srand(time(NULL));
for(int i =0 ;i<100000;i++){
a[i]= rand()%100000;
b[i]= rand()%100000;
}
clock_t start1,end1;
float res1;
start1= clock();
selectionSort(a, 100000);
end1 = clock();
res1=(float)(end1-start1);
cout<<"selection sort time : " <<res1<<"ms"<<endl;
clock_t start,end;
float res;
start= clock();
mergeSort(b, 0, 99999);
end = clock();
res=(float)(end-start);
cout<<"merge sort time: "<<res<<"ms"<<endl;
checkSort(a, 100000);
checkSort(b, 100000);
cout<<"Nurjol 12190180"<<endl;
return 0;
}