×

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

C++ operator

In this article, we will discuss about the operators in C++ with their types and examples. An operator is specially a symbol that tells compiler to perform specific manipulation. C++ contains...

5 minutes read.

Constructor Overloading

The program contains more than one constructor in a class with the same name, and different types of arguments are called constructor overloading. Calling of constructor depends on the number and types...

2 minutes read.

C++ Reading file

In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file. Syntax file-stream-class   file-stream-object;   file-stream-object.read((char *)&var , sizeof (var)); <h3">Example ofstream  outfile;         outfile . read((char*)&emp,sizeof(emp)); C++ File Handling read() Function Example Reading the content of existing...

2 minutes read.

C++ Comments

Comment/Remark A Comment or a Remark is text that is ignored by the compiler yet is beneficial to programmers. Code is usually annotated with comments for future reference. They are treated...

3 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

Diamond Pattern 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...

5 minutes read.

Preventing Object Copy in C++

C++ is an object-oriented programming language that provides the ability to create objects, define class and pass objects to functions. When passing an object to a function or returning an...

7 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples. What is the goto statement in C++? In C++, the...

4 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

For Loop Examples in C++

For Loop A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax of for loop In C++, a...

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.

Pthreads or POSIX Threads in C++

The thread API for C/C++ is implemented by pthreads or POSIX threads. It enables the multithreading system, which enables parallel and distributed processing, and the creation of new concurrent process...

3 minutes read.