Interview Question Categories

TRIVIAL FUZZY SORT IMPL

TRIVIAL FUZZY SORT IMPL

namespace TrivialFuzzySort
{
    class Interval
    {
        public int low;
        public int high;
        public int avg;

        public Interval(int l, int h)
        {
            low = l;
            high = h;
            avg = (l + h) / 2;
        }

        public Interval(Interval i)
        {
            low = i.low;
            high = i.high;
            avg = i.avg;
        }
    }

    class Program
    {
        public static void sort(Interval[] arr, int left, int right)
        {
            Interval pivot;
            int l_holder, r_holder;

            l_holder = left;
            r_holder = right;
            pivot = arr[left];

            while (left < right)
            {
                while ((arr[right].avg >= pivot.avg) && (left < right))
                {
                    right--;
                }

                if (left != right)
                {
                    arr[left] = arr[right];
                    left++;
                }

                while ((arr[left].avg <= pivot.avg) && (left < right))
                {
                    left++;
                }

                if (left != right)
                {
                    arr[right] = arr[left];
                    right--;
                }
            }

            arr[left] = pivot;
            int pivot_index = left;
            left = l_holder;
            right = r_holder;

            if (left < pivot_index)
            {
                sort(arr, left, pivot_index - 1);
            }

            if (right > pivot_index)
            {
                sort(arr, pivot_index + 1, right);
            }
        }

        static void Main(string[] args)
        {
            Interval[] intervals = { 
                                       new Interval(1,2),
                                       new Interval(2,7),
                                       new Interval(3,5),
                                       new Interval(4,8),
                                       new Interval(2,8),
                                    };
            sort(intervals, 0, intervals.Length-1);
        }
    }
}

No comments:

Post a Comment