Sunday, 29 April 2012

Program for Insertion Sort in C++



#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int main()
  {
  const int MAX = 5;
  int a[MAX+1];
  srand((unsigned)time(0));
  for(int i=1; i<MAX+1; i++)
    {
    a[i] = (rand()%100)+1;
    cout << a[i] << "  ";
    }
  cout << "(Initial array)" << "\n";

  int tempv;
  int stop;
  int count;
  int stopnow;
  for(int z=2; z<=MAX; z++)
    {
    tempv = a[z];
    stop = 0;
     count = 1;
     stopnow = 0;
     while (stopnow == 0)
       {
       if (tempv < a[count])
         {
      for (int j=z; j>=count; j--)
        {
        a[j] = a[j-1];
        }
      a[count] = tempv;
      stop = 1;
      for (int i = 1; i<= MAX; i++)
        {
        cout << a[i] << "  ";
        }
      cout << "\n";
      }
     count = count + 1;
     if ((stop == 1) || (count == z))
       {
      stopnow = 1;
      }
     }

    }
    for(int i=1; i<MAX+1; i++)
      {
      cout << a[i] << "  ";
      }
    cout << "(Sorted array)" << "\n";
    cout << "\nPress ENTER to continue..." << endl;
    getchar();
  }

No comments:

Post a Comment