我的合并排序算法如下所示......
我们知道这个算法需要额外的内存。有没有办法只用一个数组进行排序? (在单个数组中排序。)
我的合并排序算法是:
//LeftPos = start of left half;
//RightPos = start of right half
void Merge(int A[ ], int LeftPos, int RightPos, int RightEnd)
{
int LeftEnd = RightPos – 1;
int TmpPos = 1
int NumElements = RightEnd – LeftPos + 1;
int TempArray[NumElements];
while(leftPos <= LeftEnd && RightPos <= RightEnd)
if(A[LeftPos] <= A[RightPos])
TmpArray[TmpPos++] = A[LeftPos++];
else
TmpArray[TmpPos++] = A[RightPos++];
while(LeftPos <= LeftEnd) //Copy rest of first half
TmpArray[TmpPos++] = A[LeftPos++];
while(RightPos <= RightEnd) //Copy rest of second half TmpArray[TmpPos++] = A[RightPos++];
for(int i = 1; i <= NumElements; i++) //Copy TmpArray back
A[LeftPos++] = TmpArray[i];
}
答案 0 :(得分:0)
检查以下链接:
How to sort in-place using the merge sort algorithm?
符合您问题的Java代码:
https://github.com/bakeraj4/In-Place-Merge-Sort/blob/master/mergeMain.java
您正在寻找的技术是&#34;到位&#34;,对于将来的搜索,您可以使用它来在互联网上找到更好的结果。