Created
February 10, 2020 16:44
-
-
Save bpmct/493cb890891ebc7ba16ef35b77d4e335 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Collections.Generic; | |
namespace NumberSort | |
{ | |
class Program | |
{ | |
// the definition of the delegate function data type | |
delegate double sortingFunction(double[] a); | |
static void Main(string[] args) | |
{ | |
// declare the unsorted and sorted arrays | |
double[] aUnsorted; | |
double[] aSorted; | |
List<double> aUnsortedList = new List<double>(); | |
List<double> aSortedList = new List<double>(); | |
// declare the delegate variable which will point to the function to be called | |
sortingFunction findHiLow; | |
// a label to allow us to easily loop back to the start if there are input issues | |
start: | |
Console.WriteLine("Enter a list of space-separated numbers"); | |
// read the space-separated string of numbers | |
string sNumbers = Console.ReadLine(); | |
// split the string into the an array of strings which are the individual numbers | |
string[] sNumber = sNumbers.Split(' '); | |
// initialize the size of the unsorted array to 0 | |
int nUnsortedLength = 0; | |
// a double used for parsing the current array element | |
double nThisNumber; | |
// iterate through the array of number strings | |
foreach (string sThisNumber in sNumber) | |
{ | |
// if the length of this string is 0 (ie. they typed 2 spaces in a row) | |
if (sThisNumber.Length == 0) | |
{ | |
// skip it | |
continue; | |
} | |
try | |
{ | |
// try to parse the current string into a double | |
nThisNumber = double.Parse(sThisNumber); | |
aUnsortedList.Add(nThisNumber); | |
// if it's successful, increment the number of unsorted numbers | |
++nUnsortedLength; | |
} | |
catch | |
{ | |
// if an exception occurs | |
// indicate which number is invalid | |
Console.WriteLine($"Number #{nUnsortedLength + 1} is not a valid number."); | |
// loop back to the start | |
goto start; | |
} | |
} | |
//Make the sorted list | |
aSortedList = aUnsortedList.GetRange(0, aUnsortedList.Count); | |
//Sort the list | |
aSortedList.Sort(); | |
// prompt for <a>scending or <d>escending | |
Console.Write("Ascending or Descending? "); | |
string sDirection = Console.ReadLine(); | |
//Reverse if descending | |
if (sDirection.ToLower().StartsWith("d")) | |
aSortedList.Reverse(); | |
// write the sorted array of numbers | |
Console.WriteLine("The sorted list is: "); | |
foreach (double thisNum in aSortedList) | |
{ | |
Console.Write($"{thisNum} "); | |
} | |
Console.WriteLine(); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment