c++ - I write a the merge sort, but it has some bug -
i write small project implement merge sort. code:
template <typename t> void merge(t arr[], int begin, int mid, int end) { int len = end - begin + 1; t *temp = new t[len]; int = 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; } sometime got right answer, sometime got wrong answer. problem confuses me lot of time, when can find bug?
yes , rand() implementation different in both platforms, old post in stackoverflow,pls refer link here
Comments
Post a Comment