The some code, but i have different result on Windows and Linux
i write small project to implement merge sort. This is my code:
template <typename T>
void merge(T arr[], int begin, int mid, int end)
{
int len = end - begin;
T *temp = new T[len];
int i = begin;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= end)
{
if(arr[i] <= arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
while (i <= mid)
temp[k++] = arr[i++];
while(j <= end)
temp[k++] = arr[j++];
memcpy(arr + begin, temp, len*sizeof(T));
}
//merge sort
template <typename T>
void mergeSort(T arr[], int begin, int end)
{
if (begin >= end)
return;
int mid = (end + begin) / 2;
mergeSort(arr, begin, mid);
mergeSort(arr, mid + 1, end);
merge(arr, begin, mid, end);
}
int main()
{
const int N = 10;
int arr[N];
for_each(arr, arr + N, [](int &val){ val = rand() % 100; });
copy(arr, arr+N, ostream_iterator<int>(cout, " "));
cout<<endl;
mergeSort(arr, 0, N - 1);
copy(arr, arr+N, ostream_iterator<int>(cout, " "));
cout<<endl;
}
I have this reslut on Windows:
41 67 34 0 69 24 78 58 62 64
0 24 34 41 34 58 58 62 64 64
Press any key to continue . . .
But on Linux, i have the different result:
flybird@flybird ~/cplusplus_study $ g++ -std=c++11 mergeSort.cpp
flybird@flybird ~/cplusplus_study $ ./a.out
83 86 77 15 93 35 86 92 49 21
15 21 21 35 77 83 77 86 21 21
No comments:
Post a Comment