#include <iostream>
#include <cstdlib>
using namespace std;
void print(int a[], int sz)
{
for (int i = 0; i < sz; i++) cout << a[i] << " ";
cout << endl;
}
void merge(int a[], const int low, const int mid, const int high)
{
int *temp = new int[high-low+1];
int left = low;
int right = mid+1;
int current = 0;
// Merges the two arrays into temp[]
while(left <= mid && right <= high)
{
if(a[left] <= a[right])
{
temp[current] = a[left];
left++;
}
else { // if right element is smaller that the left
{
// if right element is smaller that the left
temp[current] = a[right];
right++;
}
current++;
}
// Fills the array
// The temp array has already been filled
// Use the right side of array to fill temp
if(left > mid)
{
for(int i=right; i <= high;i++)
{
temp[current] = a[i];
current++;
}
}
// Use the left side of array to fill temp
else
{
for(int i=left; i <= mid; i++)
{
temp[current] = a[i];
current++;
}
}
//Fill into original array
for(int i=0; i<=high-low;i++)
{
a[i+low] = temp[i];
}
delete[] temp;
}
void merge_sort(int a[], const int low, const int high)
{ // <-- Error #68
if(low >= high) return;
int mid = (low+high)/2;
merge_sort(a, low, mid); //left half
merge_sort(a, mid+1, high); //right half
merge(a, low, mid, high); //merge them
}
int main()
{ //<-- Error #77
int a[] = {26, 5, 33, 6, 19, 69, 99};
int arraySize = sizeof(a)/sizeof(int);
print(a, arraySize);
merge_sort(a, 0, (arraySize-1));
print(a, arraySize);
return 0;
} //<-- Error #87
//此代碼應該實現C++中的合併排序算法。 但是,當我編譯我的代碼時,它會遇到一堆錯誤。合併排序算法編譯錯誤[幫助]
mergesort.cpp: In function ‘void merge(int*, int, int, int)’:
mergesort.cpp:68: error: a function-definition is not allowed here before ‘{’ token
mergesort.cpp:77: error: a function-definition is not allowed here before ‘{’ token
mergesort.cpp:87: error: expected ‘}’ at end of input
我已表明,其中誤差修改是在代碼 誰能幫助我嗎?
你有'else {//如果正確...',然後另一個'{'在下一行你可能只想做'else // if right ...'。 – 2015-03-31 04:32:16
哇..菜鳥的錯誤。感謝兄弟,修好了! – 2015-03-31 04:35:57