Home > OS >  So I'm trying to sort the list in ascending order without using the sort function in C# and I&#
So I'm trying to sort the list in ascending order without using the sort function in C# and I&#

Time:09-10

namespace Activity4 
{
  class Worksheet4
  {
    static void Main(string[] args)
    {

//I'm limiting the user input to just 5

      List<int> Nums = new List<int>();
      while (Nums.Count < 5)
      {

            Console.Write("Enter the 1st number:");
            int Nums1 = Convert.ToInt32(Console.ReadLine());
            Nums.Add(Nums1);
            Console.Write("Enter the 2nd number:");
            int Nums2 = Convert.ToInt32(Console.ReadLine());
            Nums.Add(Nums2);
            Console.Write("Enter the 3rd number:");
            int Nums3 = Convert.ToInt32(Console.ReadLine());
            Nums.Add(Nums3);
            Console.Write("Enter the 4th number:");
            int Nums4 = Convert.ToInt32(Console.ReadLine());
            Nums.Add(Nums4);
            Console.Write("Enter the 5th number:");
            int Nums5 = Convert.ToInt32(Console.ReadLine());
            Nums.Add(Nums5);
          

here's the part where I don't really know how I am supposed to sort it in ascending order without using the sort function and if there is a simpler way for me to individually identify each input which one is lower or not please do enlighten me

            foreach (int x in Nums)
            {
              Console.WriteLine(x);
            }
         }   
      }
   }
}

CodePudding user response:

You can use LINQ's OrderBy:

var sortedAscending = Nums.OrderBy(n => n);
foreach(int num in sortedAscending)
{
    Console.WriteLine(x);
}

If you want the opposite direction use OrderByDescending.

Both methods don't create a new collection and don't modify the source-collection. They are using deferred execution, which means that they are just the instruction to perform the sort, not the actual sorting. If you want to create a new collection you can append ToList or ToArray.

They are using a stable sort(unlike List.Sort), so the order of equal numbers will stay same.

CodePudding user response:

Here is a simple logic if you don't want to use any Sort or OrderBy function.

List<int> UnSortedNums = new List<int>();
UnSortedNums.Add(20);
UnSortedNums.Add(50);
UnSortedNums.Add(40);
UnSortedNums.Add(10);
UnSortedNums.Add(30);

List<int> AscendingNums = new List<int>();
List<int> DescendingNums = new List<int>();

for (int i = 0; i < UnSortedNums.Count; i  )
{
    // For Ascending
    AscendingNums.Add(UnSortedNums.Where(x => !AscendingNums.Contains(x)).Min());

    // For Descending
    DescendingNums.Add(UnSortedNums.Where(x => !DescendingNums.Contains(x)).Max());
}
  • Related