Algorithm + Code
Algorithm + Code
3. If the element matches the target, return the index of the element.
5. Repeat steps 2 and 3 until you reach the end of the array.
2. Set low to the first index (0) and high to the last index (n-1) of the array.
If the element at mid equals the target, return mid (element found).
If the element at mid is less than the target, set low = mid + 1 (search
the right half).
If the element at mid is greater than the target, set high = mid - 1
(search the left half).
Write a C program -
1. Linear Search Program in C
1 #include <stdio.h>
2
3 int linearSearch(int arr[], int n, int target) {
4 for (int i = 0; i < n; i++) {
5 if (arr[i] == target) {
6 return i; // Return the index if element is found
7 }
8 }
9 return -1; // Return -1 if element is not found
10 }
11
12 int main() {
13 int arr[] = {2, 4, 6, 8, 10, 12};
14 int n = sizeof(arr) / sizeof(arr[0]);
15 int target;
16
17 printf("Enter the element to search: ");
18 scanf("%d", &target);
19
20 int result = linearSearch(arr, n, target);
21
22 if (result != -1) {
23 printf("Element found at index %d\n", result);
24 } else {
25 printf("Element not found\n");
26 }
27
28 return 0;
29 }
1 #include <stdio.h>
2
3 int binarySearch(int arr[], int n, int target) {
4 int low = 0, high = n - 1;
5
6 while (low <= high) {
7 int mid = low + (high - low) / 2;
8
9 if (arr[mid] == target) {
10 return mid; // Return the index if element is
found
11 }
12
13 if (arr[mid] < target) {
14 low = mid + 1; // Search in the right half
15 } else {
16 high = mid - 1; // Search in the left half
17 }
18 }
19 return -1; // Return -1 if element is not found
20 }
21
22 int main() {
23 int arr[] = {2, 4, 6, 8, 10, 12};
24 int n = sizeof(arr) / sizeof(arr[0]);
25 int target;
26
27 printf("Enter the element to search: ");
28 scanf("%d", &target);
29
30 int result = binarySearch(arr, n, target);
31
32 if (result != -1) {
33 printf("Element found at index %d\n", result);
34 } else {
35 printf("Element not found\n");
36 }
37
38 return 0;
39 }
Algorithm For Sorting
1. Bubble Sort Algorithm
Bubble Sort compares adjacent elements and swaps them if they are in the
wrong order.
Input:
Steps:
1. For i = 0 to n - 2 :
For j = 0 to n - i - 2 :
2. End.
Input:
Steps:
1. For i = 1 to n - 1 :
Decrement j .
Input:
Steps:
1. For i = 0 to n - 2 :
Set minIdx = i .
For j = i + 1 to n - 1 :
2. End.
Input:
Steps:
Input:
l : Left index.
r : Right index.
Steps:
1. If l < r :
Calculate m = (l + r) / 2 .
Subarray from l to m .
Subarray from m + 1 to r .
2. End.
Input:
2. For i = n - 1 to 1 :
3. End.
Heapify Steps:
4. If largest != i :
2. Steps:
2. Otherwise:
Increment top by 1.
2. Steps:
2. Otherwise:
Decrement top by 1.
Input:
Output:
Queue with the new element added, or an error message if the queue is
full.
Steps:
Input:
Steps:
If front > rear (queue becomes empty after dequeue), reset front
and rear to -1 .
Example Flow
Enqueue:
Dequeue: