can anyone tell me why sorting is not working in the below code..........

using System;
class stringarray
{
 public static void Main()
 {
  int n,i;
  string [] str= new string[10]; 
  Console.WriteLine("enter the limit:");
  n=int.Parse(Console.ReadLine());
  for(i=0;i<n;i++)
  {
  str[i]=Console.In.ReadLine();
  }
  Array.Sort(str); 

  for(i=0;i<n;i++)
  {
   Console.WriteLine("\n"+str[i]);
  }
 }
}

You have to define which value to put into an array. This is happening in 12. row of your code.
Try to change the code into:

Console.WriteLine("enter the limit:");
            int n = int.Parse(Console.ReadLine());
            int[] str = new int[n];
            for (int i = 0; i < n; i++)
            {
                str[i] = i;
            }
            Array.Sort(str);

            for (int i = 0; i < n; i++)
            {
                Console.WriteLine(str[i]+Environment.NewLine);
            }
            Console.ReadLine();

Try this, fill in 2 and see what happens and compare with your code:

class Program
    {
        static void Main(string[] args)
        {
            int n, i; 
            string[] str = new string[10]; 
            Console.WriteLine("enter the limit:"); 
            n = int.Parse(Console.ReadLine()); 
            for (i = 0; i < n; i++) 
            { 
                str[i] = Console.ReadLine(); 
            } 
            Array.Sort(str);
            for (i = 0; i < str.Length; i++) 
            { 
                Console.WriteLine("   [{0}] : {1}", i, str[i]); 
            }
            Console.ReadKey();
        }
    }

Did you see you are sorting empty strings?

Edited 5 Years Ago by ddanbe: n/a

now the output comes like this.............

OUTPUT
enter the limit:
5
k
b
a
e
c
[0] :
[1] :
[2] :
[3] :
[4] :
[5] : a
[6] : b
[7] : c
[8] : e
[9] : k

Edited 5 Years Ago by Jessurider: n/a

You declared an array to hold 10 strings, you only filled in 5.
When the Sort method executes it puts the 5 empty strings in front of the rest.

This article has been dead for over six months. Start a new discussion instead.