-
Notifications
You must be signed in to change notification settings - Fork 0
/
practical1.cpp
94 lines (82 loc) · 2.43 KB
/
practical1.cpp
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
#include<bits/stdc++.h>
using namespace std;
void bubbleSort(vector<int>& arr, int length)
{
for(int i = 0 ; i < length-1 ; i++)
for(int j = 1; j < length-i ; j++)
if(arr[j-1]> arr[j]) swap(arr[j-1] , arr[j]);
}
void insertionSort(vector<int>& arr , int length){
for(int i = 1; i < length ; i++){
int temp = arr[i];
int j=i-1;
while(j >= 0){
if(arr[j] > temp)
arr[j+1] = arr[j];
else
break;
j--;
}
arr[j+1] = temp;
}
}
void selectionSort(vector<int>& arr , int length){
for(int i = 0 ; i < length-1 ; i++){
int min = i;
for(int j = i+1 ; j < length ; j++){
if(arr[j] < arr[min]) min = j;
}
if(min != i)
swap(arr[i],arr[min]);
}
}
void print(vector<int>& arr , int length, auto start, auto end){
cout << "\n";
for(int i = 0 ; i < length ; i++)
cout << arr[i] << " ";
cout << "\n~~Time analysis~~";
cout << "\nIn nanoseconds : " << chrono::duration_cast<chrono::nanoseconds>(end - start).count() << "ns";
cout << "\nIn microseconds : " << chrono::duration_cast<chrono::microseconds>(end - start).count() << "µs";
cout << "\nIn milliseconds : " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << "ms";
cout << "\n~~Time analysis~~";
}
int main()
{
vector<int> arr;
int size , temp;
cout << "\nEnter number of elements you want to sort : ";
cin >> size;
for(int i = 0 ; i < size ; i++){
cin >> temp;
arr.push_back(temp);
}
int ch = 0;
cout << "\n1] Bubble sort\n2] Indertion sort\n3] Selection Sort\n4] Exit\nEnter choice :";
cin >> ch;
auto start = chrono::steady_clock::now();
switch(ch){
case 1: {
bubbleSort(arr, size);
auto end = chrono::steady_clock::now();
print(arr, size, start, end);
break;
}
case 2: {
insertionSort(arr, size);
auto end = chrono::steady_clock::now();
print(arr, size, start, end);
break;
}
case 3: {
selectionSort(arr, size);
auto end = chrono::steady_clock::now();
print(arr, size, start, end);
break;
}
case 4:
break;
default:
cout << "Error : Invalid choice. \n";
break;
}
}