Switch to full style
For C/C++ coders discussions and solutions
Post a reply

Insertion Sort (C++)

Tue Apr 10, 2007 2:13 pm

This is a type of elements sorting techniques that iterate on each element of array and put it in the right position in the array.
Code:
#include<iostream>
#include<conio.h>
using namespace std;
void main(){
// C++ Insertion Sort Example
char ch='Y';
do
{
    // Create New One
int array[50];
    // variable carry
int numbersCount;
cout<<"How many numbers you want to sort?- "<<endl;
cin>>numbersCount;
for(
int i=0;i<numbersCount;i++){
    cout<<"\nGive me the numbers:- ";
cin>>array[i];
}


    int tempArray[30];
    tempArray[0] = array[0];
    // Loop on all numbers
    for (int i = 1; i < numbersCount; i++)
    {
      
        int temp 
= array[i];
        int j = i - 1;
    // insert to the array until find number smaller than current one.
        while (( tempArray[j] > temp) && (j>=0))
        {
            tempArray[j+1] = tempArray[j];
            j--;
        }
        tempArray[j+1] = temp;
    }
    for (int k = 0; k < numbersCount; k++)
    {
        array[k] = tempArray[k];
    }

cout<<"Insertion sorting is done..."<<endl;
cout<<"The sorted numbers are"<<endl;
for(
int z=0;z<numbersCount;z++){
cout<<array[z]<<",";
 
}

// To Start Again
cout<<"\n Do you want to sort other numbers(Y/N)"<<endl;
ch=getch();
}while(
ch=='Y');

}
 


The complexity of insertion sort algorithm is o(n^2) , this algorithm works fast for small data



Re: Insertion Sort (C++)

Sun Dec 16, 2012 9:59 pm

Updated.

Post a reply
  Related Posts  to : Insertion Sort (C++)
 Java Insertion Sort Code     -  
 list insertion sorting code in c++     -  
 C++ Recursion Sort     -  
 Array sort     -  
 C++ Bubble Sort     -  
 C++ Selection Sort     -  
 Library Sort     -  
 sort words in c++     -  
 String Sort     -  
 selection sort     -  

Topic Tags

C++ Sorting