Search code examples
c#algorithmsortingselection-sort

Selection-sort algorithm sorting wrong


Okay I'm having a problem with the selection sort algorithm. It'll sort ints just fine but when I try to use it for doubles it starts to sort randomly.
here's my code

   using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sorter.ListSort;
using System.Collections;

namespace ConsoleApp20
{
    class Program
    {
        static void Main(string[] args)
        {
            var x = new List<double>();
            x.Add(23.1);
            x.Add(1.5);
            x.Add(3);
            x.Add(15.23);
            x.Add(101.2);
            x.Add(23.35);
            var sorted = selectionSort(x);

            foreach (double s in sorted)
                Console.WriteLine(s);
            Console.ReadLine();
        }

        public static List<double> selectionSort(List<double> data)
        {
            int count = data.Count;
           // Console.WriteLine(count);

            for (int i = 0; i < count - 1; i++)
            {
                int min = i;
                for (int j = i + 1; j < count; j++)
                {


                    if (data[j] < data[min])
                        min = j;

                    double temp = data[min];
                    data[min] = data[i];
                    data[i] = temp;
                }
            }

            return data;
        }
    }
}

Now this is what the algorithm is returning

enter image description here As we can see 3 is NOT bigger than 15.23, what's going on?


Solution

  • Like MoreON already mentioned in the comments, you should swap the elements after you've found the min value.

    So it should look like this

        public static List<double> selectionSort(List<double> data)
        {
            int count = data.Count;
            // Console.WriteLine(count);
    
            for (int i = 0; i < count - 1; i++)
            {
                int min = i;
                for (int j = i + 1; j < count; j++)
                {
                    if (data[j] < data[min])
                        min = j;
                }
                double temp = data[min];
                data[min] = data[i];
                data[i] = temp;
            }
    
            return data;
        }
    

    But if you don't want to reinvent the wheel, you could also use:

    var sorted = x.OrderBy(o => o).ToList();