Calling the below code with
divide(A, 1);
Should illustrate the problem
void divide(int A[], int n){
if(n==2){ // first time n==1 so no, further calls are n==0 so also no.
for(int i=0; i<2; i++)
if(A[i]>A[i+1]){
int temp=A[i];
A[i]= A[i+1];
}
} else{
divide(A, n/2); // for both n==1 and n== 0 => n==0, calls divide(A, 0)
divide(A,(n/2)+1 ); // calls divide(A, 1) always
}
}
So the program will forever call divide(A, 0) until you run out of memory.
To stop this eternal recursion you need a correct stop condition
if (n<=2) {
// correct code for swapping 1 or 2 elements
} else
You could also check for incorrect values of n, which is 0, negative and larger than length of A.
Lets say you have A[]= {1,2,3} so you call
divide(A, 3);
Now in the else part of the program you need to split up A in to parts, N/2 elements and the rest.
divide(A, n/2);
in our example this gives n/2 = 3/2 = 1 so
divide(A, 1);
and starting in the element just after the n/2'th element
divide(A+(n/2), n-(n/2));
the first element is at A[0], so the remaining start at A[1] and contains n-(n/2)=3-(3/2)=3-1=2 elements.
And now the first if, it looks like a bubble-sort, but fails as it address an element beyond the end of the array.
if(n<=2 && n>=1){
for(int i=0; i<n; i++)
if(A[i]>A[i+1]) {
A[i+1] is beyond the end of the array for i=1 and n=2, n=2 => 2 elements at address A[0] and A[1] so A[i+1]=A[2] which is not part of the array A with length 2.
for(int i=0; i<n-1; i++)
solves that and also takes care of the case with n=1, which means the array contains only one element, which by definition is already sorted.
Now if the algorithm was called divide-sort you would be finished, but you still are missing the merge part.
divide(A, 3)? And, subsequently,divide(A, 1)?divide(A, 0)in other words). OK simply - this recursion never ends.