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:-
  • Step 1: Start
  • Step 2: Input array elements
  • Step 3: Compare adjacent elements
  • Step 4: Swap if they are in wrong order
  • Step 5: Repeat steps 3-4 until array is sorted
  • Step 6: Display sorted array
  • Step 7: Stop

  • 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:-
  • Step 1: Start
  • Step 2: Get sorted array and search element
  • Step 3: Find middle element
  • Step 4: Compare search element with middle element
  • Step 5: Update search range based on comparison
  • Step 6: Repeat until element is found or not found
  • Step 7: Stop

  • 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;
    }