C# program to sort an array using quick sort

When we search for specific information, some articles do not find the information we need. But we hope you find the ideas you need in the C# program to sort an array using quick sort article. Let’s go into the article.

C# program to sort an array using quick sort

C# program to sort an array using quick sort

//C# program to sort an array using quick sort

using System;

class Sort
{
    private int[] intArray;
    
    //Initialize array
    public Sort(int []arr)
    {
        intArray = new int[arr.Length];
        intArray = arr;

    }
    public void QuickSort(int low, int high)
    {
        int pivot    =0;
        int left     =0;
        int right    =0;

        left = low;
        right = high;
        pivot = intArray[low];

        while (low < high)
        {
            while ((intArray[high] >= pivot) && (low < high))
            {
                high--;
            }

            if (low != high)
            {
                intArray[low] = intArray[high];
                low++;
            }

            while ((intArray[low] <= pivot) && (low < high))
            {
                low++;
            }

            if (low != high)
            {
                intArray[high] = intArray[low];
                high--;
            }
        }

        intArray[low] = pivot;
        pivot = low;
        low = left;
        high = right;

        if (low < pivot)
        {
            QuickSort(low, pivot - 1);
        }

        if (high > pivot)
        {
            QuickSort(pivot + 1, high);
        }
    }

    public static void Main()
    {
        int[] arr = { 12,21,13,32,34,43,77,42 };
     
        Sort sort = new Sort(arr);

        int length  = 0;
        int loop    = 0;

        length = arr.Length;

        sort.QuickSort(0,length-1);

        Console.WriteLine("Sorted array:");
        for (loop = 0; loop < length; loop++)
        {
            Console.Write(sort.intArray[loop]+" ");
        }
        Console.WriteLine();
    }
}
Sorted array:
12 13 21 32 34 42 43 77
Press any key to continue . . .

Final Words

We hope you enjoy the article C# program to sort an array using quick sort. The reason for that is that we hope that all your doubts and all doubts will be resolved through this article. Thanks

Hi, I'm Selva a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment