Total members 11889 |It is currently Fri Mar 29, 2024 3:21 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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



_________________
Please recommend my post if you found it helpful


Author:
Beginner
User avatar Posts: 109
Have thanks: 5 time

Updated.

_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 2 posts ] 

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



Topic Tags

C++ Sorting
cron





Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com