-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy patharrays.h
112 lines (104 loc) · 2.03 KB
/
arrays.h
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
#include <iostream>
using namespace std;
int linear_search(int a[], int s, int n)
{
int i;
for (i = 0; i < n; ++i)
if (a[i] == s)
return i;
return -1;
}
int binary_search(int a[100], int key, int n)
{
int beg = 0, end = n - 1, mid;
while (beg <= end)
{
mid = (beg + end) / 2;
if (a[mid] == key)
return mid;
else if (a[mid] > key)
end = mid - 1;
else
beg = mid + 1;
}
return -1;
}
int insertion(int a[], int s, int n)
{
int i, j, pos = -1;
if (a[0] > s)
pos = 0;
for (i = 0; i < n; ++i)
if (a[i] <= s && a[i + 1 > s])
pos = i + 1;
if (a[n - 1] < s)
pos = n;
for (j = n; j >= pos; --j)
a[j + 1] = a[j];
a[pos] = s;
return ++n;
}
int deletion(int a[], int s, int n)
{
int i, j, pos = -1;
for (i = 0; i < n; ++i)
{
pos = -1;
if (a[i] == s)
pos = i;
if (pos != -1)
{
for (j = pos; j < n; ++j)
a[j] = a[j + 1];
a[j] = 0;
--n, --i;
}
}
return n;
}
void selection_sort(int a[], int n)
{
int i, j, small, pos;
for (j = 0; j < n; ++j)
{
small = a[j];
for (i = j; i < n; ++i)
{
if (a[i] < small)
{
small = a[i];
pos = i;
}
if (a[j] > small)
swap(a[j], a[pos]);
}
}
}
void bubble_sort(int a[], int n)
{
int i, j;
for (i = 0; i < n - 1; ++i)
for (j = 0; j < n - i - 1; ++j)
if (a[j] > a[j + 1])
swap(a[j], a[j + 1]);
}
void insertion_sort(int a[], int n)
{
int i, j, k;
for (i = 1; i < n; ++i)
{
k = a[i];
for (j = i - 1; a[j] > k && j >= 0; --j)
a[j + 1] = a[j];
a[j + 1] = k;
}
}
void print_array(int a[], int n)
{
cout << endl;
for (int i = 0; i < n; ++i)
{
cout << a[i] << ' ';
}
cout << endl;
}