#include
#include
using namespace std;
void merge( vector& a, int first, int mid, int last )
{
vector s1;
for (auto si = a.begin() + first; si <= a.begin() + mid; ++si)
s1.push_back( *si );
vector s2;
for (auto si = a.begin() + mid + 1; si <= a.begin() + last; ++si)
s2.push_back( *si );
int i = 0; int j = 0; int k = 0;
int len1 = mid - first + 1;
int len2 = last - mid;
for (; ( i < len1 ) && ( j < len2 ); ++k)
{
if (s1[ i ] < s2[ j ])
a[ k ] = s1[ i++ ];
else
a[ k ] = s2[ j++ ];
}
while (i++ < len1)//調試到這裡顯示越界,但是此時i = 0,len1 = 1,怎麼也想不通為什麼會越界
a[ k++ ] = s1[ i ];
while (j++ < len2)
a[ k++ ] = s2[ j ];
}
void mergesort( vector& a, int first, int last )
{
if (first < last)
{
int mid = ( first + last ) / 2;
mergesort( a, first, mid );
mergesort( a, mid + 1, last );
merge( a, first, mid, last );
}
}
int main()
{
vector a = { 44, 3, 38, 5, 47, 25, 36, 26, 27, 2, 46, 4, 5, 50,99 };
mergesort( a, 0, a.size()-1 );
for (auto i : a)
cout << i<<" ";
cout << endl;
return 0;
}
i++
->
++i
否則下面i=1了