below is my code - i can get the numbers to generate but they will not sort. i need to use the merge sort method for sorting. i also need to make this array size whatever the user wants - but it will have to go up to 1000000.
can someone point out why my numbers are not sorting? I've been testing with small values such as 4 or 5.
can someone point out why my numbers are not sorting? I've been testing with small values such as 4 or 5.
Code:
#include <iostream> #include <cstdlib> #include <cmath> #include <time.h> using namespace std; int a[10], aSize; void merge(int,int,int); void merge_sort(int low, int high); void merge_sort(int low, int high) { int mid, temp; if (low==high) //this works - checking if there's one element return; if (low+1==high) // checking if there are only 2 elements { if (low>high) //compare the two elements { temp=high; //swap if low is greater than high high=low; low=temp; } } else if(low<high) { mid=(low+high)/2; merge_sort(low,mid); merge_sort(mid+1,high); merge(low,mid,high); }} void merge(int low,int mid,int high) { int size, p, q, i; //, r; int c[10]; //array c - the temporary array for sorting size = high - low + 1; //size of array c c[size]; p=low; //index for a[i]...a[mid] q=mid+1; //index for a[mid + 1]...a[j] while((p<=mid)&&(q<=high)) { if(a[p]<=a[q]) { c[i]=a[p]; //copy smaller value to local array c p++; } else { c[i]=a[q]; q++; } i++; } while (a[p]<= mid)//copy the rest of the longer array { c[i] = a[p]; } while (a[q]<=high)//copy the rest of the larger array { c[i]=a[q]; } for (i=low; i<=high; i++)//copy back from temp array to main array { a[i]=c[i]; }} int main() { long timeElapsed; timeElapsed = clock(); int i,elem; a[aSize]; cout<<"*********************************************************************"<<endl; cout<<" MERGE SORT PROGRAM"<<endl; cout<<"**********************************************************************"<<endl<<endl<<endl; cout<<"Please Enter THE NUMBER OF ELEMENTS you want to sort[THEN PRESS ENTER]:"<<endl; cin>>aSize; for (i=0; i<aSize; i++) { elem =((rand()*9)+1); cout<<endl<<"element "<<i<<"is "<<elem<<endl; a[i]= elem; cout<<"When i is "<<i<<" ai is "<<a[i]; } merge_sort(0,aSize); cout<<endl<<"So, the sorted list (using MERGE SORT) will be : "<<endl; for(i=0;i<aSize;i++) { cout<<a[i]<<" "; } cout<<endl<<endl<<"Time Elapsed is: "<<timeElapsed<<endl<<endl<<endl<<endl; system("PAUSE"); return 0; }
Comment