Implement in C#, Modify the algorithm so that it can sort strings.Its input will
ID: 3595648 • Letter: I
Question
Implement in C#, Modify the algorithm so that it can sort strings.Its input will be an array, type of which is string. The algorith will sort the elements in array. Finally, its output will be sorted array.
public void SelectionSortC()
{
int min, temp;
Console.WriteLine("");
for (int outer = 0; outer <= upper; outer++)
{
Console.Write("in iteration {0}, the partially sorted array is -----------------------------", outer);
DisplayElements();
Console.WriteLine("");
min = outer;
Console.WriteLine("* assume the min element is arr[{0}] ={1}, now start to sort", min, arr[min]);
for (int inner = outer + 1; inner <= upper; inner++)
{
if (arr[inner] < arr[min])
{
min = inner;
Console.WriteLine(" - find a smaller element, now min element should arr[{0}] ={1}", min,arr[min]);
}
}
temp = arr[outer];
arr[outer] = arr[min];
arr[min] = temp;
Console.Write("now, swap arr[{0}]={1} and arr[2]={3}, the partially sorted array is ----------",
outer, arr[outer], min, arr[min]);
DisplayElements();
Console.WriteLine(" ");
}
}
Explanation / Answer
public void SelectionSortC<A>(A[] arr)
{
int min, temp;
Console.WriteLine("");
for (int outer = 0; outer <= upper; outer++)
{
Console.Write("in iteration {0}, the partially sorted array is -----------------------------", outer);
DisplayElements();
Console.WriteLine("");
min = outer;
Console.WriteLine("* assume the min element is arr[{0}] ={1}, now start to sort", min, arr[min]);
for (int inner = outer + 1; inner <= upper; inner++)
{
if ( arr[inner].CompareTo(arr[min]) < 0 )
{
min = inner;
Console.WriteLine(" - find a smaller element, now min element should arr[{0}] ={1}", min,arr[min]);
}
}
temp = arr[outer];
arr[outer] = arr[min];
arr[min] = temp;
Console.Write("now, swap arr[{0}]={1} and arr[2]={3}, the partially sorted array is ----------",
outer, arr[outer], min, arr[min]);
DisplayElements();
Console.WriteLine(" ");
}
}
This will Sort array of Strings. Thanks, let meknow if there is any doubt/concern.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.