Insertion Sort Program in C++ Using Array

Insertion sort program in c++ basic set of sorting algorithm in c++ programming language. Insert the every new values in the sorting. This method is known as insertion sorting program.

#include <iostream>
using namespace std;
void array(int array[], int size) 
{
for (int i = 0; i < size; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
void sort(int array[], int size) 
{
for (int step = 1; step < size; step++) 
{
int key = array[step];
int j = step - 1;
while (key < array[j] && j >= 0) 
{
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
int main() 
{
int data[] = {10,56,34,78,9};
int size = sizeof(data) / sizeof(data[0]);
sort(data, size);
cout << "After sorting\n";
array(data, size);
}

 

Output:

After sorting 9 10 34 56 78

Void in C++

The void keyword, when used as a function return type, indicates that the function does not return a value. 

When used as a parameter list for a function, void indicates that the function takes no parameters.

Sizeof C++ Program

The sizeof keyword is a compile-time operator for determining the size of a variable or data type in bytes. 

The sizeof operator can be used to find the size of any user-defined data type, including classes, structures, unions, and arrays. 

The following is the syntax for using sizeof: type of data size. 

Using this program we can execute c++ program for insertion sort.

Array Concept in C++

An array is a collection of elements of the same kind that are stored in contiguous memory locations and may be accessed separately using a unique identifier’s index. 

With the help of examples, we will learn how to declare, initialise, and access array elements in C++ programming. 

A variable in C++ that can store several values of the same type is called an array.