C++ sort insertion sort example details

  • 2020-05-24 05:57:40
  • OfStack

Sort -- insert sort

The basic idea of insertion sort is to insert one record at a time, by its keyword size, into the appropriate place in the previously sorted subfile until the insertion of all the records is complete. Common insertion sorts are insertion sorts (Insertion Sort), hill sorts (Shell Sort), 2-fork lookup tree sorts (Tree Sort), library sorts (Library Sort), and Patience sorts (Patience Sort).

Simple example:


#include <iostream>
using namespace std;

void InsertSort( int k[], int n )
{
  int i, j,temp;
  
  for( i=1; i < n;i++ )
  {
    if( k[i] < k[i-1] )
    {
      temp = k[i];
      
      for( j=i-1; k[j] > temp;j-- ) // Find your position and move backwards  
      {
        k[j+1] = k[j];
      }
      
      k[j+1] = temp;
    }
  }
}

int main()
{
  int i ,a[10] = {5,2,6,0,3,9,1,7,4,8};
  
  InsertSort(a,10);
  
  for( i=0; i < 10 ;i++ )
  {
    cout << a[i];
  }
  
  cout << endl;
  
  return 0;
}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: