HereĀ  I am going to write a program to sort a String Array in Ascending Order.

C# Program to Sort a String Array in Ascending Order.

Create a Console application in C# and write the following code in Program.cs file.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArraySorting
{
class Program
{
static void Main(string[] args)
{

Console.WriteLine("Enter Number of Items to Sort");
int iItemCount = Convert.ToInt32(Console.ReadLine());
string[] sName =new string[iItemCount];
Console.WriteLine("Enter Array item to Sort");
for (int iCount = 0; iCount < iItemCount; iCount++)
{
sName[iCount] = Console.ReadLine();
}
string sTemp = string.Empty;
try
{
for (int iCount = 1; iCount < iItemCount; iCount++)
{
for (int jCount = 0; jCount < sName.Length - iCount; jCount++)
{
if (sName[jCount].CompareTo(sName[jCount + 1]) > 0)
{
sTemp = sName[jCount];
sName[jCount] = sName[jCount + 1];
sName[jCount + 1] = sTemp;
}
}
}
Console.WriteLine("Array String in Ascending Order");
for (int iCount = 0; iCount < sName.Length; iCount++)
{
Console.WriteLine(sName[iCount] + " ");
}
Console.ReadKey();
}

catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

Output:

 Sort a String Array in Ascending Order

View More:

Conclusion:

Hope this post is helpful for you. Your valuable Feedback, Comments and Suggestions are always welcome.

Thank You.

 

Leave a Comment