Thu Dec 12 2019

Insertion Sort

C++ Programming1578 views

File Name: insertion-sort.cpp

/* Insertion Sort using Template */
#include<iostream>
using namespace std;

/* Preprocessor */
#define get_size(array) (sizeof((array))/sizeof((array[0])))

template<class t>
class sorting {
	public:
		sorting(t *list, int size) {

			/* Sorting data using insertion sort algorithm */
			for(int i = 1; i < size; i++) {
				for(int j = i; j > 0; j--) {
					if(list[j] < list[j-1]) {
						t temp = list[j-1];
						list[j-1] = list[j];
						list[j] = temp;
					}
				}
			}
		}
};

int main() {

	/* Sort integer */
	int idata[] = {9,5,1,4,0,3,7,6,2,8};
	sorting<int> isrt(idata, get_size(idata));
	cout << "\nAfter sort:" << endl;
	for(int i = 0; i < get_size(idata); i++)
		cout << idata[i] << endl;

	/* Sort float */
	float fdata[] = {9.5,5.12,1.32,4.4,0.3,3.4,7.8,6.9,2.7,8.9};
	sorting<float> fsrt(fdata, get_size(fdata));
	cout << "\nAfter sort:" << endl;
	for(int i = 0; i < get_size(fdata); i++)
		cout << fdata[i] << endl;

	/* Sort string */
	string sdata[] = {"to","be","add","java","c++","python","sorting","new","search","c"};
	sorting<string> ssrt(sdata, get_size(sdata));
	cout << "\nAfter sort:" << endl;
	for(int i = 0; i < get_size(sdata); i++)
		cout << sdata[i] << endl;

}



/* Output */
After sort:
0
1
2
3
4
5
6
7
8
9


After sort:
0.3
1.32
2.7
3.4
4.4
5.12
6.9
7.8
8.9
9.5


After sort:
add
be
c
c++
java
new
python
search
sorting
to
Reference:

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.