-2

I have read recently that C# uses Quicksort algorithm to sort an array. What I would like to know whether C# uses recursive approach or iterative approach?

What I have found is this link and it looks to me that they use iterative approach. I am just wondering whether it is true that C# uses iterative implementation of QuickSort algorithm?

0

1 Answer 1

1

Two things:

  1. C# moved away from QuickSort to IntrospectiveSort, as also your link shows. You can see the comments and compatibility support at the Sort source code.

  2. The code you refer to is recursive. Near the end of the loop is a recursive call:

    private void IntroSort(int lo, int hi, int depthLimit)
    {
        while (hi > lo)
        {
            int partitionSize = hi - lo + 1;
            if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
            {
                // ... 
                InsertionSort(lo, hi);
                return;
            }
            // ...
            int p = PickPivotAndPartition(lo, hi);
            IntroSort(p + 1, hi, depthLimit); // <--- recursive call
            hi = p - 1;
        }
    }
    

    The next iteration of the loop takes the left partition, and the recursive call takes the right partition.

Sign up to request clarification or add additional context in comments.

7 Comments

The recursive call on the the right partition occurs before the loop back to take care of the left partition.
Thank you for your answer! I am just wondering why they use recursive approach? I am asking because I often heard and listened that recursion is less performant than iterative approach.
Recursion is iteration is recursion anyway..?
Sorry, @flackoverstow, I don't understand what you want to say.
Maybe that would help explain my point: an iterative approach using a stack and a recursive approach using the stack, are essentially no different.. The performance thus would essentially be no different; we aren't going to find that Sort() sped up 10x by switching away from the recursive approach employed
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.