Monday, November 16, 2009

c# Quick Sort Algorithm Implementation

private void QuickSort( int[] a, int left, int right ) 
        { 
            if( a == null ) 
                return; 
            int i = left; 
            int j = right; 
            int pivot = a[( left + right ) / 2]; 
            while( i <= j ) 
            { 
                while( a[i] < pivot ) 
                    i++; 
                while( a[j] > pivot ) 
                    j--; 
                if( i <= j ) 
                { 
                    int tmp = a[i]; 
                    a[i++] = a[j]; 
                    a[j--] = tmp; 
                } 
            } 
            if( j > left ) 
            { 
                QuickSort( a, left, j ); 
            } 
            if( i < right ) 
            { 
                QuickSort( a, i, right ); 
            } 
        }

4 comments:

Anonymous said...

i think that should be "
if (j > left) Quicksort(a, left, j);
"

Anonymous said...

After execution it throws Stack Overflow.

Anonymous said...

It works when you change if condition

replace
if(j>0)
with
if(j>left)

Anonymous said...

with if (j > left) it works very well.
can you explain to me how this algorithm?