Algorithms in C++ Programming
What is an Algorithm in C++?
An algorithm in C++ is a step-by-step procedure or set of rules designed to solve a specific problem. It is a finite sequence of well-defined instructions that can be implemented in a programming language.
- Purpose: Algorithms provide a systematic approach to problem-solving and help in creating efficient solutions.
- Types: Common algorithms include sorting, searching, recursion, and dynamic programming.
- Benefits: They help in optimizing code performance and solving complex problems efficiently.
Algorithm for Bubble Sort Implementation:-
Example 1: Bubble Sort Algorithm
#include <iostream> void bubbleSort(int arr[], int n) { for(int i = 0; i < n-1; i++) { for(int j = 0; j < n-i-1; j++) { if(arr[j] > arr[j+1]) { // Swap elements int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr)/sizeof(arr[0]); bubbleSort(arr, n); std::cout << "Sorted array: "; for(int i = 0; i < n; i++) { std::cout << arr[i] << " "; } return 0; }
Algorithm for Binary Search Implementation:-
Example 2: Binary Search Algorithm
#include <iostream> int binarySearch(int arr[], int left, int right, int x) { while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == x) return mid; if (arr[mid] < x) left = mid + 1; else right = mid - 1; } return -1; } int main() { int arr[] = {2, 3, 4, 10, 40}; int n = sizeof(arr)/sizeof(arr[0]); int x = 10; int result = binarySearch(arr, 0, n-1, x); if(result == -1) std::cout << "Element not found"; else std::cout << "Element found at index " << result; return 0; }