33,010
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
template<typename T>
int BinarySearch(T a[], const T& x, int nLeft, int nRight)
{
int nMiddle;
while (nLeft <= nRight)
{
nMiddle = (nLeft + nRight) / 2;
if (x == a[nMiddle])
return nMiddle;
if (x > nMiddle)
nLeft = nMiddle + 1;
else
nRight = nMiddle - 1;
}
if (x > a[nMiddle])
return nMiddle;
else
return nMiddle - 1;
}
template<typename T>
void ShiftLeft(T a[], int s, int t, int k)
{
T temp;
for (int i = 0; i < k; i++)
{
temp = a[t];
for (int j = t; j > s; j--)
a[j] = a[j - 1];
a[s] = temp;
}
}
template<typename T>
void Mergefor(T a[], int k, int n)
{
int i = 0;
int j = k;
int p;
while (i < j && j < n)
{
p = BinarySearch(a, a[i], j, n - 1);
ShiftLeft(a, i, p, p - j + 1);
i += j - p + 2;
j = p + 1;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[10] = {3, 5, 6, 7, 16, 2, 8, 9, 11, 12};
int b[10] = {3, 5, 6, 7, 16, 2, 4, 9, 11, 12};
Mergefor(a, 5, 10);
Mergefor(b, 5, 10);
for (int i = 0; i < 10; i++)
cout<<a[i]<<" ";
cout<<endl;
for (int j = 0; j < 10; j++)
cout<<b[j]<<" ";
cout<<endl;
return 0;
}