HiveBrain v1.2.0
Get Started
← Back to all entries
debugcsharpMinor

Optimizing error-sorting method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortingerroroptimizingmethod

Problem

I just made this sort method. It runs fine and the code looks okay in my eyes.

Is is possible to optimize it so it runs faster? If it's \$O(n^3)\$ now, it would be interesting changing it to \$O(n^2)\$ or something like that.

Side question: This is \$O(n^3)\$, right (I only like \$O(n^2)\$ and below)?

List errors = _logHandler.GetErrors(daysBack);
        List errorsSorted = new List();
        for (int i = 0; i  tempList = new List();
                    tempList.AddRange(errorsSorted.GetRange(j, 
                        errorsSorted.Count - j));

                    errorsSorted[j] = errors[i]; // replace at bigger date index
                    inserted = true;

                    errorsSorted.RemoveRange(j+1, errorsSorted.Count - (j+1));

                    // move all bigger dates one place to the right..
                    foreach (Log log in tempList) 
                    {
                        errorsSorted.Add(log);
                    }
                    break;
                }
            }
            if (!inserted)
            {
                errorsSorted.Add(errors[i]); // No date is bigger, add at the end
            }
        }

Solution

You are just sorting by date, correct? I'd use

using System.Linq;
// ....
List errors = _logHandler.GetErrors(daysBack);
List errorsSorted = errors.OrderBy(l => l.Date).ToList();


According to this stackoverflow question, OrderBy uses QuickSort in this case, which usually has a run time of O(n log n).

Code Snippets

using System.Linq;
// ....
List<Log> errors = _logHandler.GetErrors(daysBack);
List<Log> errorsSorted = errors.OrderBy(l => l.Date).ToList();

Context

StackExchange Code Review Q#6279, answer score: 4

Revisions (0)

No revisions yet.