-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathw3_1.cpp
More file actions
80 lines (66 loc) · 1.69 KB
/
Copy pathw3_1.cpp
File metadata and controls
80 lines (66 loc) · 1.69 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
#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++){
for(int j = i+1;j<n;j++){
cmp++;
if(arr[i] >arr[j]){
swp++;
swap(arr[i],arr[j]);
}
}
}
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){
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);
print_array(arr);
return 0;
}