-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab 2 Question 1 C.cpp
More file actions
76 lines (69 loc) · 1.21 KB
/
Lab 2 Question 1 C.cpp
File metadata and controls
76 lines (69 loc) · 1.21 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
//Muhammad Ghazi
//Lab 2 Question 1 C
#include <iostream>
#define length 20
using namespace std;
void sort(int A[], int size);
int main()
{
int n;
int A[length];
int mid, left, right;
left = 0;
right = length - 1;
cout << "Enter a number." << endl;
cin >> n;
cout << "Array before sorting: " << endl;
for (int i = 0; i < length; i++)
{
A[i] = rand() % 100;
cout << A[i] << " ";
}
cout << endl << endl << endl;
sort(A, length);
cout << "Array after sorting: " << endl;
for (int i = 0; i < length; i++)
{
cout << A[i] << " ";
}
cout << endl;
cout << "************************" << endl << endl;
while (left <= right)
{
mid = (left + right) / 2;
if (A[mid] == n)
{
cout << "The number was found at position " << (mid + 1) << endl;
break;
}
else if (A[mid] > n)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
if (left > right)
{
cout << "Number wasnt found." << endl;
break;
}
}
return 0;
}
void sort(int A[], int size)
{
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (A[i] > A[j])
{
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
}
}