0% found this document useful (0 votes)
7 views

Algorithm + Code

Uploaded by

Sanindra YT
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Algorithm + Code

Uploaded by

Sanindra YT
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Write an Algorithm -

1. Linear Search Algorithm


1. Start from the first element of the array.

2. Compare the current element with the target element.

3. If the element matches the target, return the index of the element.

4. If not, move to the next element.

5. Repeat steps 2 and 3 until you reach the end of the array.

6. If the target element is not found, return -1 (indicating not found).

2. Binary Search Algorithm


1. Ensure the array is sorted.

2. Set low to the first index (0) and high to the last index (n-1) of the array.

3. While low is less than or equal to high :

Calculate the middle index: mid = (low + high) / 2 .

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).

4. If the target is not found after the loop, return -1 .

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 }

2. Binary Search Program in C

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:

arr[] : Array to be sorted.

n : Number of elements in the array.

Steps:

1. For i = 0 to n - 2 :

For j = 0 to n - i - 2 :

If arr[j] > arr[j + 1] :

Swap arr[j] and arr[j + 1] .

2. End.

2. Insertion Sort Algorithm


Insertion Sort builds the sorted array one element at a time.

Input:

arr[] : Array to be sorted.

n : Number of elements in the array.

Steps:

1. For i = 1 to n - 1 :

Set key = arr[i] and j = i - 1 .

While j >= 0 and arr[j] > key :

Move arr[j] to arr[j + 1] .

Decrement j .

Insert key at arr[j + 1] .


2. End.

3. Selection Sort Algorithm


Selection Sort repeatedly finds the minimum element and places it at the
beginning.

Input:

arr[] : Array to be sorted.

n : Number of elements in the array.

Steps:

1. For i = 0 to n - 2 :

Set minIdx = i .

For j = i + 1 to n - 1 :

If arr[j] < arr[minIdx] , set minIdx = j .

Swap arr[i] and arr[minIdx] .

2. End.

4. Quick Sort Algorithm


Quick Sort uses the divide-and-conquer technique by selecting a pivot and
partitioning the array.

Input:

arr[] : Array to be sorted.

low : Starting index.

high : Ending index.

Steps:

1. If low < high :

Partition the array:

Choose pivot = arr[high] .

Rearrange elements such that elements smaller than pivot are to


its left and larger to its right.
Return the partition index pi .
Recursively call Quick Sort for:

Subarray from low to pi - 1 .

Subarray from pi + 1 to high .


2. End.

5. Merge Sort Algorithm


Merge Sort divides the array into two halves, sorts them, and then merges
them.

Input:

arr[] : Array to be sorted.

l : Left index.

r : Right index.

Steps:

1. If l < r :

Calculate m = (l + r) / 2 .

Recursively call Merge Sort for:

Subarray from l to m .

Subarray from m + 1 to r .

Merge the two sorted halves.

2. End.

6. Heap Sort Algorithm


Heap Sort builds a max heap and extracts the maximum element one by one.

Input:

arr[] : Array to be sorted.

n : Number of elements in the array.


Steps:

1. Build a max heap:

For i = n / 2 - 1 down to 0 , call heapify(arr, n, i) .

2. For i = n - 1 to 1 :

Swap arr[0] (max element) with arr[i] .

Reduce the heap size by 1 and call heapify(arr, i, 0) to restore the


heap property.

3. End.

Heapify Steps:

1. Set largest = i , left = 2 * i + 1 , and right = 2 * i + 2 .

2. If left < n and arr[left] > arr[largest] , set largest = left .

3. If right < n and arr[right] > arr[largest] , set largest = right .

4. If largest != i :

Swap arr[i] and arr[largest] .

Recursively call heapify(arr, n, largest) .


Write a C program for Bubble Sort
1 #include <stdio.h>
2
3 void bubbleSort(int arr[], int n) {
4 for (int i = 0; i < n - 1; i++) {
5 for (int j = 0; j < n - i - 1; j++) {
6 if (arr[j] > arr[j + 1]) {
7 // Swap adjacent elements if they are in the
wrong order
8 int temp = arr[j];
9 arr[j] = arr[j + 1];
10 arr[j + 1] = temp;
11 }
12 }
13 }
14 }
15
16 void printArray(int arr[], int n) {
17 for (int i = 0; i < n; i++) {
18 printf("%d ", arr[i]);
19 }
20 printf("\n");
21 }
22
23 int main() {
24 int arr[] = {64, 34, 25, 12, 22, 11, 90};
25 int n = sizeof(arr) / sizeof(arr[0]);
26
27 printf("Original array: ");
28 printArray(arr, n);
29
30 bubbleSort(arr, n);
31
32 printf("Sorted array: ");
33 printArray(arr, n);
34
35 return 0;
36 }
37
Write a C program for Selection Sort
1 #include <stdio.h>
2
3 void selectionSort(int arr[], int n) {
4 for (int i = 0; i < n - 1; i++) {
5 int minIdx = i;
6 for (int j = i + 1; j < n; j++) {
7 if (arr[j] < arr[minIdx]) minIdx = j;
8 }
9 int temp = arr[minIdx];
10 arr[minIdx] = arr[i];
11 arr[i] = temp;
12 }
13 }
14
15 void printArray(int arr[], int n) {
16 for (int i = 0; i < n; i++) printf("%d ", arr[i]);
17 printf("\n");
18 }
19
20 int main() {
21 int arr[] = {64, 25, 12, 22, 11};
22 int n = sizeof(arr) / sizeof(arr[0]);
23
24 printf("Original array: ");
25 printArray(arr, n);
26
27 selectionSort(arr, n);
28
29 printf("Sorted array: ");
30 printArray(arr, n);
31
32 return 0;
33 }

Write a C program for Insertion Sort


1 #include <stdio.h>
2
3 void insertionSort(int arr[], int n) {
4 for (int i = 1; i < n; i++) {
5 int key = arr[i];
6 int j = i - 1;
7 while (j >= 0 && arr[j] > key) {
8 arr[j + 1] = arr[j];
9 j--;
10 }
11 arr[j + 1] = key;
12 }
13 }
14
15 void printArray(int arr[], int n) {
16 for (int i = 0; i < n; i++) printf("%d ", arr[i]);
17 printf("\n");
18 }
19
20 int main() {
21 int arr[] = {12, 11, 13, 5, 6};
22 int n = sizeof(arr) / sizeof(arr[0]);
23
24 printf("Original array: ");
25 printArray(arr, n);
26
27 insertionSort(arr, n);
28
29 printf("Sorted array: ");
30 printArray(arr, n);
31
32 return 0;
33 }

Write a C program for Quick Sort


1 #include <stdio.h>
2
3 void swap(int *a, int *b) {
4 int temp = *a;
5 *a = *b;
6 *b = temp;
7 }
8
9 int partition(int arr[], int low, int high) {
10 int pivot = arr[high];
11 int i = low - 1;
12
13 for (int j = low; j < high; j++) {
14 if (arr[j] < pivot) {
15 i++;
16 swap(&arr[i], &arr[j]);
17 }
18 }
19 swap(&arr[i + 1], &arr[high]);
20 return i + 1;
21 }
22
23 void quickSort(int arr[], int low, int high) {
24 if (low < high) {
25 int pi = partition(arr, low, high);
26 quickSort(arr, low, pi - 1);
27 quickSort(arr, pi + 1, high);
28 }
29 }
30
31 void printArray(int arr[], int n) {
32 for (int i = 0; i < n; i++) printf("%d ", arr[i]);
33 printf("\n");
34 }
35
36 int main() {
37 int arr[] = {10, 7, 8, 9, 1, 5};
38 int n = sizeof(arr) / sizeof(arr[0]);
39
40 printf("Original array: ");
41 printArray(arr, n);
42
43 quickSort(arr, 0, n - 1);
44
45 printf("Sorted array: ");
46 printArray(arr, n);
47
48 return 0;
49 }

Write a C program for Merge Sort


1 #include <stdio.h>
2
3 void merge(int arr[], int l, int m, int r) {
4 int n1 = m - l + 1;
5 int n2 = r - m;
6 int L[n1], R[n2];
7
8 for (int i = 0; i < n1; i++) L[i] = arr[l + i];
9 for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j];
10
11 int i = 0, j = 0, k = l;
12 while (i < n1 && j < n2) {
13 if (L[i] <= R[j]) arr[k++] = L[i++];
14 else arr[k++] = R[j++];
15 }
16
17 while (i < n1) arr[k++] = L[i++];
18 while (j < n2) arr[k++] = R[j++];
19 }
20
21 void mergeSort(int arr[], int l, int r) {
22 if (l < r) {
23 int m = l + (r - l) / 2;
24 mergeSort(arr, l, m);
25 mergeSort(arr, m + 1, r);
26 merge(arr, l, m, r);
27 }
28 }
29
30 void printArray(int arr[], int n) {
31 for (int i = 0; i < n; i++) printf("%d ", arr[i]);
32 printf("\n");
33 }
34
35 int main() {
36 int arr[] = {12, 11, 13, 5, 6, 7};
37 int n = sizeof(arr) / sizeof(arr[0]);
38
39 printf("Original array: ");
40 printArray(arr, n);
41
42 mergeSort(arr, 0, n - 1);
43
44 printf("Sorted array: ");
45 printArray(arr, n);
46
47 return 0;
write a C program for Heap sort
1 #include <stdio.h>
2
3 // Function to heapify a subtree rooted at index i
4 void heapify(int arr[], int n, int i) {
5 int largest = i; // Initialize largest as root
6 int left = 2 * i + 1; // Left child
7 int right = 2 * i + 2; // Right child
8
9 // If left child is larger than root
10 if (left < n && arr[left] > arr[largest])
11 largest = left;
12
13 // If right child is larger than largest so far
14 if (right < n && arr[right] > arr[largest])
15 largest = right;
16
17 // If largest is not root
18 if (largest != i) {
19 int temp = arr[i];
20 arr[i] = arr[largest];
21 arr[largest] = temp;
22
23 // Recursively heapify the affected subtree
24 heapify(arr, n, largest);
25 }
26 }
27
28 // Main function to perform heap sort
29 void heapSort(int arr[], int n) {
30 // Build max heap
31 for (int i = n / 2 - 1; i >= 0; i--)
32 heapify(arr, n, i);
33
34 // Extract elements from heap one by one
35 for (int i = n - 1; i > 0; i--) {
36 // Move current root to the end
37 int temp = arr[0];
38 arr[0] = arr[i];
39 arr[i] = temp;
40
41 // Call heapify on the reduced heap
42 heapify(arr, i, 0);
43 }
44 }
45
46 // Function to print the array
47 void printArray(int arr[], int n) {
48 for (int i = 0; i < n; i++)
49 printf("%d ", arr[i]);
50 printf("\n");
51 }
52
53 // Driver function
54 int main() {
55 int arr[] = {12, 11, 13, 5, 6, 7};
56 int n = sizeof(arr) / sizeof(arr[0]);
57
58 printf("Original array: ");
59 printArray(arr, n);
60
61 heapSort(arr, n);
62
63 printf("Sorted array: ");
64 printArray(arr, n);
65
66 return 0;
67 }
Write an Algorithm for Push &
Pop in Stack
Algorithm for Push Operation in Stack:
1. Input: The stack, the current top position, the maximum size ( MAX ), and the
value to be pushed.

2. Steps:

1. If top == MAX - 1 , print "Stack Overflow" and exit.

2. Otherwise:

Increment top by 1.

Add the value to stack[top] .

3. Print "Value pushed into the stack".

3. Output: Updated stack and top position.

Algorithm for Pop Operation in Stack:


1. Input: The stack and the current top position ( top ).

2. Steps:

1. If top == -1 , print "Stack Underflow" and exit.

2. Otherwise:

Retrieve the value from stack[top] .

Decrement top by 1.

Print "Value popped from the stack".

3. Output: Updated stack and top position.

Write a C program for Push & Pop in Stack


1 #include <stdio.h>
2 #define MAX 5 // Maximum size of the stack
3
4 int stack[MAX], top = -1;
5
6 // Push operation
7 void push(int value) {
8 if (top == MAX - 1)
9 printf("Stack Overflow\n");
10 else {
11 stack[++top] = value;
12 printf("%d pushed into the stack\n", value);
13 }
14 }
15
16 // Pop operation
17 void pop() {
18 if (top == -1)
19 printf("Stack Underflow\n");
20 else
21 printf("%d popped from the stack\n", stack[top--]);
22 }
23
24 // Display stack elements
25 void display() {
26 if (top == -1)
27 printf("Stack is empty\n");
28 else {
29 printf("Stack elements: ");
30 for (int i = top; i >= 0; i--)
31 printf("%d ", stack[i]);
32 printf("\n");
33 }
34 }
35
36 int main() {
37 push(10);
38 push(20);
39 push(30);
40 display(); // Display stack elements
41
42 pop();
43 display(); // Display after popping
44
45 return 0;
46 }
Write an Algorithm for Enqueue
& Dequeue
Algorithm for Enqueue Operation
The enqueue operation inserts an element into the queue.

Input:

queue[] : The queue array.

rear : The index of the rear of the queue.

MAX : The maximum size of the queue.

value : The element to be added.

Output:

Queue with the new element added, or an error message if the queue is
full.

Steps:

1. Check if the queue is full:

If rear == MAX - 1 , print "Queue Overflow" and exit.

2. If the queue is not full:

If front == -1 , set front = 0 (initialize front if it's the first element).

Increment rear by 1 ( rear = rear + 1 ).

Insert the value at queue[rear] .

Print a success message.

Algorithm for Dequeue Operation


The dequeue operation removes an element from the front of the queue.

Input:

queue[] : The queue array.

front : The index of the front of the queue.

rear : The index of the rear of the queue.


Output:

The dequeued element, or an error message if the queue is empty.

Steps:

1. Check if the queue is empty:

If front == -1 or front > rear , print "Queue Underflow" and exit.

2. If the queue is not empty:

Print the element at queue[front] (the element to be dequeued).

Increment front by 1 ( front = front + 1 ).

If front > rear (queue becomes empty after dequeue), reset front
and rear to -1 .

Example Flow
Enqueue:

Initial: queue = [ ], front = -1, rear = -1

Enqueue 10 : queue = [10], front = 0, rear = 0

Enqueue 20 : queue = [10, 20], front = 0, rear = 1

Dequeue:

Dequeue 10 : queue = [10, 20], front = 1, rear = 1

Dequeue 20 : queue = [10, 20], front = -1, rear = -1 (queue is


reset).

Write a C program for Enqueue & Dequeue


using queue
1 #include <stdio.h>
2 #define MAX 5 // Maximum size of the queue
3
4 int queue[MAX], front = -1, rear = -1;
5
6 // Enqueue operation
7 void enqueue(int value) {
8 if (rear == MAX - 1)
9 printf("Queue Overflow\n");
10 else {
11 if (front == -1) front = 0; // Initialize front if
it's the first element
12 queue[++rear] = value;
13 printf("%d enqueued into the queue\n", value);
14 }
15 }
16
17 // Dequeue operation
18 void dequeue() {
19 if (front == -1 || front > rear)
20 printf("Queue Underflow\n");
21 else {
22 printf("%d dequeued from the queue\n",
queue[front++]);
23 if (front > rear) front = rear = -1; // Reset queue if
empty
24 }
25 }
26
27 // Display queue elements
28 void display() {
29 if (front == -1 || front > rear)
30 printf("Queue is empty\n");
31 else {
32 printf("Queue elements: ");
33 for (int i = front; i <= rear; i++)
34 printf("%d ", queue[i]);
35 printf("\n");
36 }
37 }
38
39 int main() {
40 enqueue(10);
41 enqueue(20);
42 enqueue(30);
43 display(); // Display queue elements
44
45 dequeue();
46 display(); // Display after dequeuing
47
48 return 0;
49 }

You might also like