Monday, September 26, 2011

Implement Insertion sort in C/C++

Insertion sort is a simple sorting algorithm: a comparison sort in which the sorted array (or list) is built one entry at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.

Insertion sort

#include <iostream>
#include <cstdlib>
using namespace std;

void InsertionSort(int* ar, int len);

const int LENGTH = 10;
int data[LENGTH];

int main()
{
//Prepare data
for (int i = 0; i < 10; i++) {
data[i] = rand() % 100;
}

cout << "data before Insertion Sort:" << endl;
for (int i = 0; i < 10; i++)
cout << data[i] << " ";
cout << endl << endl;

InsertionSort(data, LENGTH);

cout << endl << "data before Insertion Sort:" << endl;
for (int i = 0; i < 10; i++)
cout << data[i] << " ";
cout << endl;

return 0;
}

void InsertionSort(int* ar, int len){
int cur, j;

for (int i = 1; i < len; i++) {
cur = ar[i];
j = i - 1;
while ((j >= 0) && (ar[j] > cur)) {
ar[j + 1] = ar[j];
j--;
}
ar[j + 1] = cur;

for (int ii = 0; ii < 10; ii++)
cout << ar[ii] << " ";
cout << endl;
}
}

No comments:

Post a Comment