So I am somewhat new to the intricacies of C++ and its memory handling.
I wrote a piece of code in which the iterator in main function is not behaving as i would expect. It is supposed to take n
inputs instead it is just exiting midway depending on the values inputted. The mergeSort
and merge
function works just fine (at least for small arrays with predefined elements) so no need to check that. The main problem is in the main
function. Any help would be appreciated.
#include<cstdio> #include<iostream> #include<sstream> using namespace std; void merge(long int *a, long int start, long int mid, long int end) { long int *c=new long int[1000000]; long int i,ptr1=0,ptr2=0,ptr=0; long int length1,length2; length1=mid-start+1; length2=end-mid; while(ptr1<length1 && ptr2<length2){ if(a[start+ptr1]>a[mid+ptr2+1]){ c[start+ptr]=a[mid+ptr2+1]; ptr++; ptr2++; } else if(a[start+ptr1]<=a[mid+ptr2+1]){ c[start+ptr]=a[start+ptr1]; ptr++; ptr1++; } } while(ptr1<length1){ c[start+ptr]=a[start+ptr1]; ptr++; ptr1++; } while(ptr2<length2){ c[start+ptr]=a[mid+ptr2+1]; ptr++; ptr2++; } for(i=0;i<ptr; i++) a[start+i]=c[start+i]; } void mergeSort(long int *a, long int start, long int end){ if(start<end){ long int mid; mid=(start+end)/2; mergeSort(a, start, mid); mergeSort(a,mid+1, end); merge(a, start, mid, end); } } /*Problem lies in Main*/ int main() { string s; int n,i,j; long int *a=new long int[1000000](); cin >> n; for(i=0;i<n;i++){ /************Loop exiting midway************/ cin >> s; stringstream g(s); g >> n; a[i]=n; } mergeSort(a,0,n-1); for(j=0; j<5; j++){ cout << a[j] << "\n"; } return 0; }
Forgive me for bad formatting of code.