forked from 7harshit20/dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray_search_and_sort.cpp
124 lines (116 loc) · 2 KB
/
array_search_and_sort.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
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
#include <iostream>
using namespace std;
void swap(int* a, int* b)
{
int temp=*a;
*a=*b;
*b=temp;
}
void linearSearch(int arr[], int n, int key)
{
bool a=false;
for(int i=0; i<n; i++)
{
if(arr[i]==key)
{
cout<<"key matches";
a=1;
break;
}
}
if(!a)
cout<<"key does not match";
}
int binarySearch(int arr[], int n, int key)
{
int a=0, b=n-1, i;
do
{
i=(a+b)/2;
if(arr[i]>key)
{
b=i;
}
else if(arr[i]<key)
{
a=i;
}
else
{
return i;
}
} while(b-a!=1);
return -1;
}
void selectionSort(int arr[], int n)
{
int minindex=0;
for(int i=0; i<n; i++)
{
for(int j=i+1; j<n; j++)
{
if(arr[j]<arr[minindex])
{
minindex=j;
}
}
swap(&arr[i], &arr[minindex]);
minindex=i+1;
}
for(int i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
}
void bubbleSort(int arr[], int n)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n-1-i; j++)
{
if(arr[j]>arr[j+1])
{
swap(&arr[j], &arr[j+1]);
}
}
}
for(int i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
}
void insertionSort(int arr[], int n)
{
for(int i=1; i<n; i++)
{
int j=i;
while(arr[j]<arr[j-1]&&j>=0)
{
swap(&arr[j], &arr[j-1]);
j--;
}
}
for(int i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
}
int main()
{
int n, key=5;
cout<<"enter the size of array \n";
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
// cout<<"enter the key \n";
// cin>>key;
// linearSearch(arr,n,key);
// cout<<"\n"<<binarySearch(arr,n,key)<<endl;
// selectionSort(arr,n);
// bubbleSort(arr,n);
// insertionSort(arr,n);
return 0;
}