×

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of some important functions which are present in a workbook called the library.

There are various types of functions present in the C++ Algorithms Library. Let us straightway look at the categories.

Min/Max:

        Function        Description
minReturn smallest element in the range
maxReturn the largest element in the range
minmaxReturn smallest and largest element
min_elementReturns smallest element
max_elementReturns largest element
minmax_elementReturns both(smallest and largest)

Merge:

        Function       Description
mergemerges two elements in sorted order
includesSearches inclusion of another range in sorted range
inplace_mergeReturns two consecutive merged range
set_unionReturn union of two sorted ranges
set_intersectionReturns intersecting sorted ranges
set_differenceReturn the difference of two ranges
set_symmetric_differenceReturns symmetric sorted difference

Sorting:

         Function         Description
sortSorts all the elements in a range
is_sortedChecks whether elements are sorted
is_sorted_untilChecks range till range of sorting
nth_elementCheck nth sorts of elements in range
partial_sortSorts range elements partially
partial_sort_copyCopies the sorted elements in range
stable_sortMaintains specific equivalent order while sorting elements in the range

The above functions are immensely used while programming. Since there are hundreds of such functions present in the STL library, we'll be discussing some of them using a coding example.

Simplest sorting algorithm: Bubble Sort

Code:

 #include<bits/stdc++.h>
 using namespace std; 
 int main() 
 { 
 #include<bits/stdc++.h>
 using namespace std;
 int main ()
 {
    int i, j,temp,pass=0;
    int a[10] = {1,2,3,4,5,6,7,8};
    cout <<"Input list: \n";
    for(i = 0; i<10; i++) {
       cout <<a[i]<<"\t";
    }
 cout<<endl;
 for(i = 0; i<10; i++) {
    for(j = i+1; j<10; j++)
    {
       if(a[j] < a[i]) {
          temp = a[i];
          a[i] = a[j];
          a[j] = temp;
       }
    }
    pass++;
 }
 cout <<"Elements after sorting: \n";
 for(i = 0; i<10; i++) {
    cout <<a[i]<<"\t";
 }
 cout<<"\nNumber of passes taken: "<<pass<<endl;
 return 0;
 } 

Output:

C++ Algorithms

Explanation:

The above code is a simple depiction of a sorting technique popularly known as Bubble Sort. Bubble sort works on the following algorithm:

 START
 Step 1:
  For i = 0 to N-1
 repeat Step 2
 Step 2:
 For J = i + 1 to N – I
 Repeat
 Step 3: if A[J] > A[i]
 Swap A[J] and A[i]
 [first loop ends]
 [second loop ends]
 END 

The first loop is started from the 0th element and the next loop is iterated from an adjacent element. In the inner loop, we compare each associated element and swap them if they are found not in order. Additionally, at the end of each iteration performed by the outer loop, the heaviest or the greatest element is bubbled up at the end.

The comparison is done using passes. Passes are nothing but the swapped value that occurs while iterating through each element. In this case, 3 passes are occurring to sort the given items. With each pass the largest element is shifted last i.e. after the first pass, the largest element is shifted last. In second pass, the largest item is shifted at 2nd last position, and so on.

Min/Max Algorithm

Minmax function example:

#include<bits/stdc++.h>

using namespace std;

int main ()

{

  auto values = minmax({100,222,324,401,500});

  cout << "Minimum and Maximum values are: ";

  cout << values.first << ' ' << values.second << endl;

  return 0;

}

Output:

C++ Algorithms

Explanation:

The above code is a simple depiction of the minmax function discussed earlier. It is present in the <algorithm> header file thus using <bits/stdc++> imports all the necessary files required. In the above code, we have defined a variable 'value' which stores all the elements given. These elements are passed as an argument to minmax function and the result is displayed on the console in the form of a minimum and maximum values.

Searching Algorithm:

Binary Search:

 #include<bits/stdc++.h>
 using namespace std;
 int binarySearch(int array[], int x, int low, int high)
 {
   while (low <= high) {
     int mid = low + (high - low) / 2;
     if (array[mid] == x)
       return mid;
     if (array[mid] < x)
       low = mid + 1;
     else
       high = mid - 1;
  }
   return -1;
 }
 int main() {
   int array[] = {5,6,8,1,9,4,10};
   int x;
   cin>>x;
   int n = sizeof(array) / sizeof(array[0]);
   int result = binarySearch(array, x, 0, n - 1);
   if (result == -1)
     cout<<"Not found";
   else
     cout<<"Element is found at index: "<<result;
 } 

Output:

C++ Algorithms

Explanation:

Binary search works on the concept of following algorithm:

 START
 Step1: x is compared to middle element.
 Step 2: Return the middle element if x matches.
 Step 3: If x is greater than middle element, it is shifted right.
 Step 4: Else x (if smaller than mid-element) is shifted left.
 END 

The binary search algorithm is typically used to find an element present in a huge data-set. It can be compared to a search of a contact in the telephone directory where the directory is divided into two equal parts and the range in which the proximity of getting element is maximum, the range yet again divided to reduce time in traversing through each element present.


Related Topics

Palindrome Number Program in C++

A palindrome number is one that is the same when it is reversed. Palindrome numbers include 22, 33, 44, 55, 66, 77, 88, and 99. Algorithm for Palindrome Numbers Get the user's...

4 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a...

4 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

wcscpy(), wcslen(), wcscmp() Functions in C++

There are many built-in functions in C++ programming language which differentiate it from C programming language in most hardware-coded languages. We will now closely look into the applications of three...

4 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

C++ Ternary Operator

In this tutorial, we'll learn about the C++ ternary operator and how to utilise it to manage the program's flow using examples. Ternary Operator: The if-else statement and the conditional operator use...

3 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.