How can I make this code with just one parameter (int[] a) ?

private void QuickSort( int[] a, int left, int right ) 
        { 
            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 > 0 ) 
            { 
                QuickSort( a, left, j ); 
            } 
            if( i < right ) 
            { 
                QuickSort( a, i, right ); 
            } 
        }

It must not include int left and int right parameters in QuickSort subroutine.

Recommended Answers

All 5 Replies

QuickSort is recursive and thus requires the 3 parameters to use. What you need to do is create a wrapper around the call:

private void DoQuickSort(int[] a) {
    QuickSort(a, 0, a.Length - 1);

OK I get it.

static void DoQuickSort(int[] a)
        {
            QuickSort(a, 0, a.Length - 1);
        }

        static void QuickSort(int[] a, int left, int right)
        {
            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 < 0)
            {
                QuickSort(a, left, j); 
            }
            if(i > right)
            {
                QuickSort(a, i, right ); 
            }
        }

Thanks for that.

But now I can't find the way to change the program that it will sort the numbers from the biggest to the smallest. What do I need to fix?

Change the < to a > in line 13 and the > to a < in line 15.

Or change DoQuicksort to

static void DoQuickSort(int[] a) {
    QuickSort(a, 0, a.Length - 1);
    a = a.Reverse().ToArray();
}

Nvm, my code is not good :(

I've found the solution.
Anyway, I would not made it without your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.