-1

I tried to implement a quicksort on arrays of int64_t like this:

void quicksort (int64_t *array,size_t size) { 
    int64_t *split;
    size_t i=0;
    size_t j=size-1;
    if (size>1) {
    split=({
      int64_t p=array[0];
      do {
           for (;array[i]<p;i++);
           for (;array[j]>p;j--);
           swap(array[i],array[j]);
      } while (i<j);
      swap(array[i],array[j]);
      swap(array[j],array[size]);
      &(array[j]);
      })-1;
    quicksort(array,j-1);
    quicksort(split+1,size-j);
    }
    return; 
}

Which is good, however, it enters into infinite recursion or infinite loop immediately after first partitioning pass. How can I solve this?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Erkin Alp Güney
  • 218
  • 6
  • 15
  • swap is defined as a macro: `#define swap(a,b) ({ \ typeof(a) __c=(a); \ a=b; \ b=__c; \ })` – Erkin Alp Güney May 24 '15 at 16:29
  • 1
    "*How can I solve this?*" compile with symbols (option `-g` for gcc) and run the code in a debugger (gdb for gcc), which allows you to trace it step by step and inspect all relevant variables. – alk May 24 '15 at 16:36
  • 0) when [5,5,5] _infinite loop_ at do-while. 1) `array[size]` is out of bounds. – BLUEPIXY May 24 '15 at 16:39

2 Answers2

0

Your partitioning code looks weird and there's at least a few things wrong with it: for (; a[i] < p; i++) is not guaranteed to terminate.

And then if j is the final position of pivot element, your left array should be sorted by quicksort(array, j) and not j-1.

Apurv
  • 32
  • 2
0

I couldn't get your code to compile (my compiler is old). But shouldn't:

size_t i=0; 

be instead initialized as 1 because you have

int64_t p=array[0];  // partition element?

and

for (;array[i]<p;i++);

That is probably not the only problem.

Angus Comber
  • 9,316
  • 14
  • 59
  • 107