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

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

python - How do I create a list index that loops through integers in another list -

c# - “System.Security.Cryptography.CryptographicException: Keyset does not exist” when reading private key from remote machine -