Stock
Stock

Reputation: 87

Sorting elements with Array.Sort() not sorting the first element

I've been using Array.Sort() to sort an array of string, but for some reason it is keeping the first element of the array and outputting not in order.

    private void quicksort1_Click(object sender, EventArgs e)
    {


        String[] parts = new String[1000];

        //System.IO.StreamReader file = new System.IO.StreamReader(textBox1.Text);
        System.IO.StreamWriter output = new System.IO.StreamWriter("OUTPUT.txt");

        parts = File.ReadAllLines(textBox1.Text);
        foreach (string s in parts)
        {
                Array.Sort(parts);
                parts.Equals(s);
                output.WriteLine(s);
                counter++;

        }
        output.WriteLine("There were" + " "  + counter + " " + "lines read in.");

        output.Close();

I was just wondering if there was a possible solution to where Array.Sort() would sort the first element as well as the others.

Upvotes: 1

Views: 1244

Answers (3)

Reed Copsey
Reed Copsey

Reputation: 564891

Right now, you're sorting the entire set once per line. Instead, you can just sort the lines once in advance of your loop.

In your current code, the first line appears unsorted because you're fetching it prior to the sort:

foreach (string s in parts) // Getting s from the original array
{
   Array.Sort(parts);  //Sorting array
   // s is unchanged - at this point its still the first element from the original array

Instead, sort up front. Try this:

private void quicksort1_Click(object sender, EventArgs e)
{
  using (var output = new System.IO.StreamWriter("OUTPUT.txt"))
  {
    string[] parts = File.ReadAllLines(textBox1.Text);
    Array.Sort(parts);
    foreach (string s in parts)
    {
        output.WriteLine(s);
    }

    output.WriteLine("There were {0} lines read in.", parts.Length);
  }

    }

Note that there is also no need for a counter variable here, and switching the code to use the using statement simplifies the logic a bit.

Upvotes: 4

Matt Houser
Matt Houser

Reputation: 36113

You are outputting the first line using the line output.WriteLine(s). The problem is that s is retrieved from your list before the list is sorted.

Upvotes: 0

kemiller2002
kemiller2002

Reputation: 115538

This needs to be outside of the loop (before the loop that is): Array.Sort(parts);

By the time you have done the sort, you're already accessing the first element. The first element is getting sorted in the Array, you've just accessed it in it's previous position in the enumeration.

Upvotes: 2

Related Questions