This code is supposed to sort an array using the divide-and-conquer method. But I think I mixed up the index.
The array to be sorted is:Code:#include <iostream> using namespace std; void Merge(float *A , int p , int q , int r) { int n1 = q - p + 1; int n2 = r - q; float *L = new float [n1]; float *R = new float [n2]; int i , j; for ( i = 0 ; i < n1 ; i++) L[i] = A[p + i -1]; for ( j = 0 ; j < n2 ; j++) R[j] = A[q + j]; i = 1; j = 1; for ( int k = p; k <= r ; k++) { if ( L[i] <= R[j]) { A[k] = L[i]; ++i; } else if (A[k] == R[j]) { ++j; } } delete [] L; delete [] R; } void Merge_Sort(float *A, int p, int r) { if ( p < r ) { int q = (p+r)/2; Merge_Sort(A,p,q); Merge_Sort(A,q+1,r); Merge(A,p,q,r); } } int main() { int n = 8; float A[] = {5,2,4,7,1,3,2,6}; for ( int i = 0 ; i < 8 ; i++) std::cout << A[i] << std::endl; Merge_Sort(A,1,7); cout << endl; for ( int i = 0 ; i < 8 ; i++) std::cout << A[i] << std::endl; return 0; }
the sorted array should be:Code:A={5,2,4,7,1,3,2,6}
However, what i get is:Code:1 2 2 3 4 5 6 7
This is just replacing the point in the middle of the original array A with 0. I don't understand why it's doing this. Any input is well appreciated.Code:5 0 0 0 0 0 0 6



LinkBack URL
About LinkBacks



