Wednesday, 13 January 2016

CSM2013: Insertion Sort source code for cpp



// Insertion Sort.cpp : Defines the entry point for the console application.
//

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

using namespace std;

void Insertion_Sort(vector<int> x, int y);

int main()
{
vector<int> List;
int s;
int t;

srand(time(nullptr));

cout << "Copyright (c) JOYTEK MOTION(tm) 2015." << endl << endl;

sort:

// Prompt the user the put the size of the list
cout << endl;
cout <<"INSERT THE SIZE OF RANDOM NUMBERS: ";
cin >> s;

// Set size of list according to what the user inputted
List.resize(s);

// Assign random values into the list
for(int i = 0; i < s; i++)
{
List[i] = rand() % 100;
}

cout << "YOUR UNSORTED LIST IS ";
for(int i = 0; i < s; i++)
cout << List[i] << " ";

Insertion_Sort(List, s);

cout << "INPUT 0 TO SORT AGAIN or 1 to Exit: ";
cin >> t;
if(t == 0)
goto sort;
cout << endl;
system("PAUSE");
return 0;
}

void Insertion_Sort(vector <int>Array, int ArraySize)
{
int i,key;

for(int j = 1; j < ArraySize; j++)
{
key = Array[j];
// Insert Array[j] into the sorted Sequence Array[1], Array[2]...Array[j-1]
i = j - 1;

while((i > -1) && (Array[i] > key))
{
Array[i + 1] = Array[i];
i = i - 1;
}
Array[i + 1] = key;
}

cout << endl << "YOUR SORTED LIST IS ";
for(int j = 0; j <  ArraySize; j++)
cout << Array[j] << " ";
cout << endl;
}
Insertion Sort(0).cpp
Open with
Prince Adolphus
(adolphusprince@gmail.com)Displaying Insertion Sort(0).cpp.

0 comments:

Post a Comment