Write a program named SortWords that includes a method named SortAndDisplayWords
ID: 3719955 • Letter: W
Question
Write a program named SortWords that includes a method named SortAndDisplayWords that accepts any number of words, sorts them in alphabetical order, and displays the sorted words separated by spaces.
I am getting close?
using System;
using static System.Console;
public class SortWords
{
public static void Main(string[] args)
{
Console.WriteLine("How many words to you want to sort?");
int size = Convert.ToInt32(Console.Readline());
int[] n = new int[size];
Console.WriteLine("Enter"+ size + " words into array.");
for(int i=0; i<size; i++)
{
n[i] = Convert.ToInt32(Console.ReadLine());
}
Program avr = new Program();
avr.SortAndDisplayWords(n);
Console.Read();
}
public static void SortAndDisplayWords(params string[] words)
{
WriteLine("help");
Explanation / Answer
using System.IO;
using System;
public class SortWords
{
public static void Main(string[] args)
{
Console.WriteLine("How many words to you want to sort?");
int size = Convert.ToInt32(Console.ReadLine());
string[] n = new string[size];
Console.WriteLine("Enter "+ size + " words into words.");
for(int i=0; i<size; i++)
{
n[i] = Console.ReadLine();
}
SortWords avr = new SortWords();
avr.SortAndDisplayWords(n);
Console.Read();
}
public void SortAndDisplayWords(params string[] words)
{
int n = words.Length;
string temp;
for (int i = 0; i < n; i++) {
int j = 1;
while (j < (n - i)) {
if (words[j - 1].CompareTo(words[j])>0) {
// swap the elements!
temp = words[j - 1];
words[j - 1] = words[j];
words[j] = temp;
}
j++;
}
}
Console.WriteLine("Given words in sorting order: ");
for (int i = 0; i < n; i++) {
Console.WriteLine(words[i]);
}
}
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.