Algorithms, Pseudo Codes, and C++ Programs
1. Linear Search
Algorithm:
1. Start
2. Take array and key as input.
3. Traverse the array from the beginning.
4. If any element matches the key, return its position.
5. If no match is found, display "Element not found."
6. Stop.
Pseudo code:
Start
Input array[ ] and key
for i = 0 to n-1 do
if array[i] == key then
Print "Element found at index i"
Exit
end if
end for
Print "Element not found"
Stop
C++ Code:
#include <iostream>
using namespace std;
int main() {
int arr[] = {5, 10, 15, 20, 25};
int n = 5, key = 15;
bool found = false;
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
cout << "Element found at index " << i << endl;
found = true;
break;
if (!found) cout << "Element not found." << endl;
return 0;
2. Binary Search
Algorithm:
1. Start
2. Take sorted array and key as input.
3. Set low = 0, high = n-1.
4. Repeat while low <= high:
- Find mid = (low + high)/2.
- If array[mid] == key, return mid.
- If array[mid] < key, set low = mid + 1.
- Else set high = mid - 1.
5. If key not found, print "Element not found."
6. Stop.
Pseudo code:
Start
Input array[ ] and key
low = 0
high = n - 1
while low <= high do
mid = (low + high) / 2
if array[mid] == key then
Print "Element found at index mid"
Exit
else if array[mid] < key then
low = mid + 1
else
high = mid - 1
end if
end while
Print "Element not found"
Stop
C++ Code:
#include <iostream>
using namespace std;
int main() {
int arr[] = {5, 10, 15, 20, 25};
int n = 5, key = 20, low = 0, high = n - 1, mid;
bool found = false;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == key) {
cout << "Element found at index " << mid << endl;
found = true;
break;
else if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
if (!found) cout << "Element not found." << endl;
return 0;
3. Insertion Sort
Algorithm:
1. Start
2. Take array as input.
3. For each element from index 1 to n-1:
- Store the current element in key.
- Compare key with previous elements.
- Shift larger elements to the right.
- Insert key at the correct position.
4. Display sorted array.
5. Stop.
Pseudo code:
Start
Input array[ ]
for i = 1 to n-1 do
key = array[i]
j=i-1
while j >= 0 and array[j] > key do
array[j + 1] = array[j]
j=j-1
end while
array[j + 1] = key
end for
Print sorted array
Stop
C++ Code:
#include <iostream>
using namespace std;
int main() {
int arr[] = {5, 3, 8, 6, 2};
int n = 5;
for (int i = 1; i < n; i++) {
int key = arr[i], j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
cout << "Sorted array: ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
return 0;