c++ - bad alloc in QuickSort -


i'm doing quicksort i'm getting bad_alloc() error.sometimes code run time i'm getting error.the program run , sort right when it's run s out of 4 times it's give me bad _alloc error. what's problem???????

#include <iostream> using namespace std; void quicksort(int *a,int,int); int main() { int i,j,*a; = new int[j]; cout<<"enter total element:"; cin>>j; for(i=0;i<j;i++){     cout<<"enter element:";cin>>a[i]; } quicksort(a,0,j-1); cout<<"after sorting."<<endl; for(i=0;i<j;i++){     cout<<a[i]<<endl; } return 0; } void quicksort(int *a,int u,int d){     int key = a[u];     int upper = u;     int lower = d;     while(key>a[u] && u<lower){         u++;     }     while(key<a[d] && d>upper){         d--;     }     if(u<d){     swap(a[u],a[d]);     quicksort(a,upper,lower);     }     if(u>=d){         swap(key,a[d]);         if(upper!=d)         {         quicksort(a,upper,d-1);         }         if(d!=lower)         {         quicksort(a,d+1,lower);         }       }    } 

move statement

a = new int[j]; 

after

cin>>j; 

you allocating "junk" j takes value whatever in local stack memory location have!


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -