Insertion sort code algorithm
Aug 28, 2013 at 7:18am UTC
[Algorithms]I trying to program an insertion sort code,my problem that it doesn't sort and the output is like the input,what can i do ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
/* Head ends here */
void insertionSort(vector <int > ar) {
int temp;
int i,j,k,x;
for (i = 0;i<ar.size();i++)
{
for (j = 0;j<ar.size();j++)
{
if (ar[j]<ar[i])
{
for (k = j;k<=i;k--)
{
temp = ar[j];
ar[k] = ar[k-1];
}
ar[i] = temp;
break ;
}
}
for (x = 0;x<ar.size();x++)
{
cout<<ar[x];
}
cout<< endl;
}
}
/* Tail starts here */
int main(void ) {
vector <int > _ar;
int _ar_size;
int _ar_tmp;
cin >> _ar_size;
for (int _ar_i=0; _ar_i<_ar_size; _ar_i++) {
cin >> _ar_tmp;
_ar.push_back(_ar_tmp);
}
insertionSort(_ar);
return 0;
}
Aug 28, 2013 at 7:33am UTC
Looks like you are loosing information on line 30 to 31 because temp is simply holding the last value in the range of that for-loop. So nothing is being swapped until that for-loop has finished execution.
Topic archived. No new replies allowed.