/*归并排序*/
void mergeArray(int* a,int* temp,int left,int mid,int right)
{
int i1 = left,i2 = mid + 1,k = 0;
while (i1 <= mid && i2 <= right)
{
if (a[i1] <= a[i2])
{
temp[k++] = a[i1++];
}
else
{
temp[k++] = a[i2++];
}
}
while (i1 <= mid)
{
temp[k++] = a[i1++];
}
while (i2 <= right)
{
temp[k++] = a[i2++];
}
for (int i = 0; i < k; i++)
{
a[left+i] = temp[i];
}
}
上面代码为合并a[left,mid]和a[mid+1,right]的代码,因为归并排序是思想是先比较然后复制到另外一个临时数组,所以这里的temp起到复制存放的作用。
void mergeSort(int* a,int* temp,int left,int right)
{
if (left < right)
{
int mid = (left + right)/2;
mergeSort(a,temp,left,mid);
mergeSort(a,temp,mid+1,right);
mergeArray(a,temp,left,mid,right);
}
}
上面代码为归并排序的代码。
int main()
{
//产生length长度的100以内随机数组成的数组
srand(time(0));
int length;
cout<<"Input the length of array:\n";
cin>>length;
int* shy_array = new int[length];
for(int i=0;i<length;i++)
{
shy_array[i] = rand()/1000;
}
//输出数组
printArray(shy_array,length);
int* temp = new int[length];
mergeSort(shy_array,temp,0,length-1);
printArray(shy_array,length);
delete[] temp;
}