Ritika Roy

Ritika Roy

  • NA
  • 2
  • 2.5k

Selection Sort using String Array in C#

Apr 16 2015 7:42 AM
Please help me to sort the string array in selection sort 
My Code show IndexOutOfRange Exception
 
 
using System;
public class StSorting
{
public static void Main()
{
Console.Write("Enter the size of String array: ");
int size = Convert.ToInt32(Console.ReadLine());
string[] arr = new string[size];
int i, j, location;
string minimum = string.Empty;
string temp = string.Empty;
Console.WriteLine("Enter the element in the array");
for(i = 0; i<size; i++)
{
Console.Write("Array[{0}] : ", i);
arr[i] = Console.ReadLine();
}
Console.WriteLine();
Console.WriteLine("Given Array is: ");
for(i = 0; i<size; i++)
{
Console.Write("{0} ", arr[i]);
}
for(i = 0; i<size; i++)
{
minimum = arr[i];
location = i;
for(j = i+1; j<size; j++)
{
if( (arr[j].CompareTo(minimum)) < 0)
{
minimum = arr[j];
location = j;
}
}
if(location != i)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Console.WriteLine("\n\nSorted array is: ");
for(i=0;i<size;i++)
{
Console.Write("{0} ", arr[i]);
}
Console.ReadKey();
}
}

Answers (2)