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
{
Console.Write("Array[{0}] : ", i);
arr[i] = Console.ReadLine();
}
Console.WriteLine();
Console.WriteLine("Given Array is: ");
for(i = 0; i
{
Console.Write("{0} ", arr[i]);
}
for(i = 0; i
{
minimum = arr[i];
location = i;
for(j = i+1; 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
{
Console.Write("{0} ", arr[i]);
}
Console.ReadKey();
}
}
2 Replies
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Abhineet SrivastavaPosted Apr 16, 2015, 1:36 PM
Hari KrishnaPosted Apr 16, 2015, 9:16 AM
The following code may helpful to you..
// Sorting logic
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;
}
}
}
}