-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bubble_and_insertionSort.c
83 lines (76 loc) · 1.61 KB
/
Bubble_and_insertionSort.c
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
#include <stdio.h>
int linearSearch(int arr[], int size, int num)
{
for (int i = 0; i < size; i++)
{
if (arr[i] == num)
{
return i;
}
}
return -1;
}
int BinarySearch(int arr[], int size, int element)
{
int low, mid, high;
low = 0;
high = size - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (arr[mid] == element)
{
return mid;
}
else if (element > arr[mid])
{
low = mid + 1;
}
else if (element < arr[mid])
{
high = mid - 1;
}
// return mid;
}
return -1;
}
void bubbleSort(int a[], int n)
{
for (int i = 1; i < n; i++)
{
for (int j = 0; j < n - i ; j++)
{
if (a[j] > a[j+1])
{
int temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
}
}
}
}
void insertionSort(int a[], int n)
{
for (int i = 1; i < n; i++)
{
int current = a[i];
int j = i - 1;
while (a[j] > current && j >= 0)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
int main()
{
int arr[] = {10, 14, 32, 35, 53, 20000000, 67, 12, 89, 1, 5, 7};
int size = sizeof(arr)/sizeof(int);
int element = linearSearch(arr, size, 32);
bubbleSort(arr, size);
int element2 = BinarySearch(arr, size, 32);
printf("the element 32 is found at %dth position\n",element);
printf("the element 32 is found at %dth position\n",element2);
return 0;
}