Close

How does insertion sort work

Insertion sort is also a comparison based sorting. It is also an in-place sorting algorithm i.e it does not require extra space. We can re-arrange the elements within the array itself.The algorithm works as follows. The array is divided into two parts one sorted and one un-sorted. Initially the sorted part will be empty and…

How does binary search work

Given an array of numbers, how do you search for a number? The simplest method is to start at the first element and keep comparing until the end of the array. If it is found anywhere in the middle, return it. Otherwise we would reach the end of the array which indicates that the element in…

Program to find nth Fibonacci number

Fibonacci number in mathematics is defined as the sum of the two previous elements in the series. Formally this is represented as f(n) = f(n-1) + f(n-2) where f(1) = 1 and f(2) = 1. In this post we will see how to generate nth fibonacci number. The algorithm is self-explanatory from the program itself. So…

How does a selection sort works

Like Bubble sort, Selection sort is also a comparison based sorting algorithm, but it uses lesser number of swappings. Selection sort works this way. In first iteration it selects the smallest element and keep it in the first place. In the second iteration it selects the next smallest element from the remaining elements and keep…

How does Bubble sort works?

Bubble sort is a comparison based sorting algorithm. It works like following.  We perform series of iterations to ‘bubble up’ the elements one by one so that they form a sorted order. For example we have to sort an array [3,1,4,5,2] in ascending order, In the first iteration, the element 5 will be bubbled up…

Program to find GCD of two numbers

In mathematics, the greatest common divisor (gcd), also known as the greatest common factor (gcf), or highest common factor (hcf), of two or more integers (at least one of which is not zero), is the largest positive integer that divides the numbers without a remainder – from WikipediaFor example, the GCD of 8 and 12…

Finding the length of a linked list

In this post we will see an algorithm to find the length of the linked list. Here singly linked list is implemented in Object Oriented Programming (OOP) paradigm in C++. The algorithm is very simple. Just start at the beginning of the linked list, move to next until you reach the end of the list,…

Member initialization list in C++

You all know that in C++, constructors are used to create an object. We normally initialize all the data members with some valid data in the constructor. We generally write code similar to the following and think that m_data variable is being initialized where as it is actually being assigned. class MyClass{ public: Myclass(int d)…