C++ example-C++ code for insertion sort


C++ example-C++ code for insertion sort

This is C++ example code for the insertion sort.

#include <cstdlib>
#include <iostream>
#include <conio.h>


using namespace std;
void insertsort(int dataset[], int n){
  int i,j;
  for(i=1;i<n;i++){
    int pick_item=dataset[i];
    bool inserted=false;
    for(j=i-1;j>=0 && inserted!=true;){
       if(pick_item<dataset[j])
      {
          dataset[j+1]=dataset[j];
          j--;
          dataset[j+1]=pick_item;
       }
      else inserted=true;
  }
 }

}

int main(){

  int arr[5]={23,2,3,34,6}; //unsorted data set
  insertsort(arr,5); //sorting process using insertion sort
  for(int i=0;i<5;i++)
    cout<<arr[i]<<"\t"; //after sorting


getch();
return 0;

}



Comments

Mohit Makhija comment

 Mohit Makhija

For Source code in c++, python and java refer the link below
http://code2begin.blogspot.com/2017/01/insertion-sort.html


2017-08-31



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.