Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 760139
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T15:40:52+00:00 2026-05-14T15:40:52+00:00

I’m trying to implement quicksort in a functional style using C# using linq, and

  • 0

I’m trying to implement quicksort in a functional style using C# using linq, and this code randomly works/doesn’t work, and I can’t figure out why.
Important to mention: When I call this on an array or list, it works fine. But on an unknown-what-it-really-is IEnumerable, it goes insane (loses values or crashes, usually. sometimes works.)
The code:

   public static IEnumerable<T> Quicksort<T>(this IEnumerable<T> source)
        where T : IComparable<T>
    {
        if (!source.Any())
            yield break;
        var pivot = source.First();
        var sortedQuery = source.Skip(1).Where(a => a.CompareTo(source.First()) <= 0).Quicksort()
                          .Concat(new[] { pivot })
                          .Concat(source.Skip(1).Where(a => a.CompareTo(source.First()) > 0).Quicksort());
        foreach (T key in sortedQuery)
            yield return key;
    }

Can you find any faults here that would cause this to fail?

Edit: Some better test code:

        var rand = new Random();
        var ienum = Enumerable.Range(1, 100).Select(a => rand.Next());
        var array = ienum.ToArray();
        try
        {
            array.Quicksort().Count();
            Console.WriteLine("Array went fine.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Array did not go fine ({0}).", ex.Message);
        }
        try
        {
            ienum.Quicksort().Count();
            Console.WriteLine("IEnumerable went fine.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("IEnumerable did not go fine ({0}).", ex.Message);
        }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T15:40:52+00:00Added an answer on May 14, 2026 at 3:40 pm

    Some enumerable instances, such as those returned by Linq to SQL or Entity Framework queries, are only designed to be iterated once. Your code requires multiple iterations and will crash or behave strangely on these types of instances. You’d have to materialize those enumerables with ToArray() or a similar method first.

    You should also be reusing that pivot so that you don’t have to keep iterating for the first and remaining elements. This may not completely solve the problem, but it’ll help in some cases:

    public static IEnumerable<T> Quicksort<T>(this IEnumerable<T> source)
        where T : IComparable<T>
    {
        if (!source.Any())
            return source;
        var pivot = source.First();
        var remaining = source.Skip(1);
        return remaining
            .Where(a => a.CompareTo(pivot) <= 0).Quicksort()
            .Concat(new[] { pivot })
            .Concat(remaining.Where(a => a.CompareTo(pivot) > 0).Quicksort());
    }
    

    (You also don’t need to iterate through the sortedQuery – just return it, it’s already an IEnumerable<T>.)

    On a related note, why do you feel the need to re-implement this functionality? Enumerable.OrderBy already does it for you.


    Response to update:

    Your tests are failing because your test is wrong, not the algorithm.

    Random is a non-deterministic input source and, as I have explained above, the sort method needs to perform multiple iterations over the same sequence. If the sequence is totally random, then it is going to get different values on subsequent iterations. Essentially, you are trying to quicksort a sequence whose elements keep changing!

    If you want the test to succeed, you need to make the input consistent. Use a seed for the random number generator:

    static IEnumerable<int> GetRandomInput(int seed, int length)
    {
        Random rand = new Random(seed);
        for (int i = 0; i < length; i++)
        {
            yield return rand.Next();
        }
    }
    

    Then:

    static void Main(string[] args)
    {
        var sequence = GetRandomInput(248917, 100);
        int lastNum = 0;
        bool isSorted = true;
        foreach (int num in sequence.Quicksort())
        {
            if (num < lastNum)
            {
                isSorted = false;
                break;
            }
            lastNum = num;
        }
        Console.WriteLine(isSorted ? "Sorted" : "Not sorted");
        Console.ReadLine();
    }
    

    It will come back sorted.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 429k
  • Answers 429k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer If you're looking for a way to do this in… May 15, 2026 at 1:35 pm
  • Editorial Team
    Editorial Team added an answer I have contact the OpenBugs develop team before, I asked… May 15, 2026 at 1:35 pm
  • Editorial Team
    Editorial Team added an answer You could do that so simply by using a transparent… May 15, 2026 at 1:35 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.