-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek_3_1.cpp
More file actions
87 lines (83 loc) · 2.05 KB
/
Copy pathweek_3_1.cpp
File metadata and controls
87 lines (83 loc) · 2.05 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
#include <bits/stdc++.h>
using namespace std;
void selection_sort(vector<int> &arr)
{
int n = arr.size();
int cmp = 0, swp = 0;
for (int i = 0; i < n - 1; i++)
{
int mi_index = i;
for (int j = i + 1; j < n; j++)
{
cmp++;
if (arr[j] < arr[mi_index])
mi_index = j;
}
swp++;
swap(arr[i], arr[mi_index]);
}
cout << "array sorted using selection sort" << "and Total Comparisons are:" << cmp << "total swaps are:" << swp << endl;
}
void bubble_sort(vector<int> &arr)
{
int n = arr.size();
int cmp = 0, swp = 0;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n - 1; j++)
{
cmp++;
if (arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
swp++;
}
}
}
cout << "array sorted using Bubble sort" << "and Total Comparisons are:" << cmp << "total swaps are:" << swp << endl;
}
void insertion_sort(vector<int> &arr)
{
int n = arr.size();
int cmp = 0, swp = 0;
for (int i = 1; i < n; i++)
{
int key = arr[i];
int j = i - 1;
cmp++;
while (j >= 0 && arr[j] > key)
5
{
arr[j + 1] = arr[j];
swp++;
cmp++;
j--;
}
arr[j + 1] = key;
}
cout << "sorting done using insertion sort" << "total comparisons are:" << cmp << "total insertionsn are:" << swp << endl;
}
void print_array(vector<int> arr)
{
cout << "printing array" << endl;
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << " ";
}
}
int main()
{
int n;
cout << "enter size of array:" << endl;
cin >> n;
vector<int> arr(n);
cout << "enter elements:" << endl;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
insertion_sort(arr);
// selection_sort(arr);
print_array(arr);
return 0;
}