Order Generic Question

advertisements

In an interview they told me

Write the code in the brackets to order the list. They said order but you dont know if the type is going to be int or decimal.

They also told me not to use framework methods like .sort

So I have no idea how would I do it? I need to be ready for the next time somebody asks me this.

Possible Inputs: 7,3,8,6,1
Or: 6.9, 4.5, 2.3, 6.1, 9.9

namespace InterViewPreparation1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSort_Click(object sender, EventArgs e)
        {
            List<int> list= new List<int>();
            list.Add(int.Parse(i1.Text));
            list.Add(int.Parse(i2.Text));
            list.Add(int.Parse(i3.Text));
            list.Add(int.Parse(i4.Text));
            list.Add(int.Parse(i5.Text));
            Sort(list);
        }

        private void Sort<T>(List<T> list)
        {
            bool madeChanges;
            int itemCount = list.Count;
            do
            {
                madeChanges = false;
                itemCount--;
                for (int i = 0; i < itemCount; i++)
                {
                    int result = Comparer<T>.Default.Compare(list[i], list[i + 1]);

                    if (result > 0)
                    {
                        Swap(list, i, i + 1);
                        madeChanges = true;
                    }
                }
            } while (madeChanges);
        }

        public  List<T> Swap<T>(this List<T> list,
                int firstIndex,
                int secondIndex)
        {
            T temp = list[firstIndex];
            list[firstIndex] = list[secondIndex];
            list[secondIndex] = temp;

            return list;
        }
    }
}


Well, both Int and Double implement IComparable - this means that you should cast each element to an IComparable when performing your sort. As you can't use any standard .Net sorting method you need to implement one yourself. See Sorting algorithm for some inspiration.

It would be easier if the method signature was different:

public void sortlist<T>(List<T> list)
    where T : IComparable
{

}

An example implementation of bubble sort:

for (int pass = 1; pass < list.Count; pass++)
{
    for (int i = 0; i < list.Count; i++)
    {
        if (list[i].CompareTo(list[i + 1]) > 0)
        {
            // Swap
            T temp = list[i];
            list[i] = list[i + 1];
            list[i + 1] = temp;
        }
    }
}

Alternatively if T isn't constrained to IComparable then you can tweak this slightly as per Marcs suggestion by using Comparer<T>.Default:

Comparer<T>.Default.Compare(list[i], list[i + 1])