R
Reetesh Mukul
I wrote following code for insertion sort. The code was compiled using
gcc-4.1.1-30 on my fedora core 6 system. For this code output is not
correct {output is 2,5,76,76,76}. It seems, "line #2" is not working.
Meanwhile no problem occurs when
1. line #1 is changed to T key = arr; or
2. line #2 is changed to T& q = arr[j+1]; q = key.
Am I missing something ?
Regards,
Reetesh Mukul
-------------------------------------------------------------------------------------------------------------------
//insertion_sort.cpp
#include <iostream>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
#include <boost/array.hpp>
using namespace boost;
using namespace boost::lambda;
using namespace std;
template<typename T, size_t N>void insertion_sort(array<T,N>& arr)
{
for(size_t i = 2; i < N ; ++i)
{
T& key = arr; //line #1
for(int j = i - 1; j >=0; --j)
{
if( key < arr[j] )
arr[j+1] = arr[j];
else{
arr[j+1] = key; //line #2
break;
}
}
}
}
int main()
{
array<int,5>a = {2,5,76,11,3};
insertion_sort(a);
for_each(a.begin(),a.end(),cout << _1<<" ");
return 0;
}
gcc-4.1.1-30 on my fedora core 6 system. For this code output is not
correct {output is 2,5,76,76,76}. It seems, "line #2" is not working.
Meanwhile no problem occurs when
1. line #1 is changed to T key = arr; or
2. line #2 is changed to T& q = arr[j+1]; q = key.
Am I missing something ?
Regards,
Reetesh Mukul
-------------------------------------------------------------------------------------------------------------------
//insertion_sort.cpp
#include <iostream>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
#include <boost/array.hpp>
using namespace boost;
using namespace boost::lambda;
using namespace std;
template<typename T, size_t N>void insertion_sort(array<T,N>& arr)
{
for(size_t i = 2; i < N ; ++i)
{
T& key = arr; //line #1
for(int j = i - 1; j >=0; --j)
{
if( key < arr[j] )
arr[j+1] = arr[j];
else{
arr[j+1] = key; //line #2
break;
}
}
}
}
int main()
{
array<int,5>a = {2,5,76,11,3};
insertion_sort(a);
for_each(a.begin(),a.end(),cout << _1<<" ");
return 0;
}