Skip to content

Instantly share code, notes, and snippets.

@Swarchal
Last active July 17, 2016 22:46
Show Gist options
  • Save Swarchal/3d4fdd6e616b2436bfa769769f42cc7c to your computer and use it in GitHub Desktop.
Save Swarchal/3d4fdd6e616b2436bfa769769f42cc7c to your computer and use it in GitHub Desktop.
insertion sort algorithm
#include <vector>
#include <iostream>
using namespace std;
// insertion-sort integers given from stdin
int main()
{
// create vector of integers
vector<signed int> v;
signed int input, tmp, idx;
// create vector from stdin
while (input != -999) {
cin >> input;
// stop -999 being added to the vector
if (input != -999) {
v.push_back(input);
}
}
// insertion-sort the vector v
for (int i=0; i<v.size(); i++) {
tmp = v[i];
idx = i;
while (i>0 && v[i-1] > tmp) {
v[i] = v[i-1];
i--;
}
if (i != idx) {
v[i] = tmp;
}
}
// print ordered vecctor to stdout
for (int j=0; j<v.size(); j++) {
cout << v[j] << " ";
}
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment