Hello, I need a program in C# that uses a generic sort function to do the follow
ID: 3815360 • Letter: H
Question
Hello, I need a program in C# that uses a generic sort function to do the following:
(i) sort numbers ascending by numerical value,
(ii) sort people alphabetically (lexicographically) by name, and to
(iii) sort people descending by age, where people of the same age should be sorted alphabetically (lexicographically).
The point here is to use the same function to do all 3 different sort operations. Try to reuse as much of your code and focus on clarity and brevity.
Data to use to sort:
The sequence of floating point numbers: (645.32, 37.40, 76.30, 5.40, -34.23, 1.11, -34.94, 23.37, 635.46, -876.22, 467.73, 62.26)
The following sequence of people with name and age of each person. The name is a string and the age an integer: (Hal, 20; Susann, 31; Dwight 19; Kassandra, 21; Lawrence, 25; Cindy, 22; Cory, 27; Mac, 19; Romana, 27; Doretha, 32; Danna, 20; Zara, 23; Rosalyn, 26; Risa, 24; Benny, 28; Juan, 33; Natalie, 25)
Explanation / Answer
using System; using System.Collections; public class ReverseComparer : IComparer { // Call CaseInsensitiveComparer.Compare with the parameters reversed. public int Compare(Object x, Object y) { return (new CaseInsensitiveComparer()).Compare(y, x ); } } public class Example { public static void Main() { // Create and initialize a new array. String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps", "over", "the", "lazy", "dog" }; // Instantiate the reverse comparer. IComparer revComparer = new ReverseComparer(); // Display the values of the array. Console.WriteLine( "The original order of elements in the array:" ); DisplayValues(words); // Sort a section of the array using the default comparer. Array.Sort(words, 1, 3); Console.WriteLine( "After sorting elements 1-3 by using the default comparer:"); DisplayValues(words); // Sort a section of the array using the reverse case-insensitive comparer. Array.Sort(words, 1, 3, revComparer); Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:"); DisplayValues(words); // Sort the entire array using the default comparer. Array.Sort(words); Console.WriteLine( "After sorting the entire array by using the default comparer:"); DisplayValues(words); // Sort the entire array by using the reverse case-insensitive comparer. Array.Sort(words, revComparer); Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:"); DisplayValues(words); } public static void DisplayValues(String[] arr) { for ( int i = arr.GetLowerBound(0); iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.