Quick sort algorithm

Write a program to demonstrate Quick sort algorithm?

Solution

For more information about Quick Sort read the article

using System;
using System.Collections.Generic;

namespace Sorting
{
    class QuickSort
    {
        static void Main()
        {
            var arr = new[] { 8, 6, 4, 2, 9, 5 };
            SortQuick(arr, 0, arr.Length - 1);

            Console.WriteLine($"Sorted:{string.Join(" ", arr)}");
            Console.ReadLine();
        }
        static int Partition(IList<int> numbers, int left, int right)
        {
            var pivot = numbers[left];
            while (true)
            {
                while (numbers[left] < pivot)
                    left++;

                while (numbers[right] > pivot)
                    right--;

                if (left < right)
                {
                    var temp = numbers[right];
                    numbers[right] = numbers[left];
                    numbers[left] = temp;
                }
                else
                {
                    return right;
                }
            }
        }

        static void SortQuick(IList<int> arr, int left, int right)
        {
            if (left >= right) return;

            var pivot = Partition(arr, left, right);

            if (pivot > 1)
                SortQuick(arr, left, pivot - 1);

            if (pivot + 1 < right)
                SortQuick(arr, pivot + 1, right);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *