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:");
for(i=0;i<n;i++)
{
}
Array.Sort(str);

for(i=0;i<n;i++)
{
Console.WriteLine("\n"+str[i]);
}
}
}``````
3
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by ddanbe

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[] 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);
}

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:");
for (i = 0; i < n; i++)
{
}
Array.Sort(str);
for (i = 0; i < str.Length; i++)
{
Console.WriteLine("   [{0}] : {1}", i, str[i]);
}
}
}``````

Did you see you are sorting empty strings?

Edited 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 by Jessurider: n/a

why the top 5 remains blank...........

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.