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 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsForums
Top experts
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Hari Krishna93 reputationPosted Apr 16, 2015, 5:16 AM EDT
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;
}
}
}
}
Abhineet SrivastavaRank #1,890 · 783 reputationPosted Apr 16, 2015, 9:36 AM EDT