C# Program to Implement Quick Sort

C# Program to Implement Quick Sort

Sorting is an essential skill in programming, and Quick Sort is one of the most efficient algorithms for organizing data. Quick Sort works on the divide-and-conquer principle, where an array is divided around a pivot element. Elements smaller than the pivot are moved to the left, and elements greater are moved to the right. This process is repeated recursively until the array is fully sorted. Quick Sort is known for its speed and efficiency, making it a favorite in real-world applications like databases, search engines, and data analytics.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Learning Quick Sort in C# helps beginners understand important programming concepts such as recursion, array manipulation, and algorithm optimization. By experimenting with predefined data examples, beginners can see how the pivot divides the array and how recursive calls sort the smaller parts. This hands-on approach makes it easier to grasp the underlying logic and prepares learners for more advanced algorithms in the future.

Program 1: Quick Sort Using Recursion (Ascending Order)

This program demonstrates the standard recursive Quick Sort algorithm, sorting a predefined array in ascending order.

using System;

class Program
{

    static int Partition(int[] arr, int low, int high)
    {

        int pivot = arr[high];
        int i = low - 1;

        for (int j = low; j < high; j++)
        {

            if (arr[j] <= pivot)
            {

                i++;

                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;

            }

        }

        int temp1 = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp1;

        return i + 1;

    }

    static void QuickSort(int[] arr, int low, int high)
    {

        if (low < high)
        {

            int pi = Partition(arr, low, high);

            QuickSort(arr, low, pi - 1);
            QuickSort(arr, pi + 1, high);

        }

    }

    static void Main()
    {

        int[] arr = { 10, 7, 8, 9, 1, 5 };

        QuickSort(arr, 0, arr.Length - 1);

        Console.WriteLine("Sorted array in ascending order:");

        foreach (int num in arr)
            Console.Write(num + " ");

        Console.WriteLine();

    }

}

In this program, the pivot is chosen as the last element of the array. The array is partitioned around the pivot so that smaller elements go to the left and larger elements to the right. Recursive calls then sort the subarrays. Beginners can see clearly how the array gradually becomes sorted through partitioning.

Program 2: Quick Sort in Descending Order

By adjusting the comparison in the partitioning step, Quick Sort can sort arrays in descending order.

using System;

class Program
{

    static int Partition(int[] arr, int low, int high)
    {

        int pivot = arr[high];
        int i = low - 1;

        for (int j = low; j < high; j++)
        {

            if (arr[j] >= pivot)
            {

                i++;

                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;

            }

        }

        int temp1 = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp1;

        return i + 1;

    }

    static void QuickSort(int[] arr, int low, int high)
    {

        if (low < high)
        {

            int pi = Partition(arr, low, high);

            QuickSort(arr, low, pi - 1);
            QuickSort(arr, pi + 1, high);

        }

    }

    static void Main()
    {

        int[] arr = { 10, 7, 8, 9, 1, 5 };

        QuickSort(arr, 0, arr.Length - 1);

        Console.WriteLine("Sorted array in descending order:");

        foreach (int num in arr)
            Console.Write(num + " ");

        Console.WriteLine();

    }

}

This version shows how a simple change in the comparison operator can reverse the sorting order. Beginners can see the flexibility of Quick Sort for different use cases.

Program 3: Quick Sort With Strings

Quick Sort can also be used to sort strings alphabetically.

using System;

class Program
{

    static int Partition(string[] arr, int low, int high)
    {

        string pivot = arr[high];
        int i = low - 1;

        for (int j = low; j < high; j++)
        {

            if (string.Compare(arr[j], pivot) <= 0)
            {

                i++;

                string temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;

            }

        }

        string temp1 = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp1;

        return i + 1;

    }

    static void QuickSort(string[] arr, int low, int high)
    {

        if (low < high)
        {

            int pi = Partition(arr, low, high);

            QuickSort(arr, low, pi - 1);
            QuickSort(arr, pi + 1, high);

        }

    }

    static void Main()
    {

        string[] arr = { "Banana", "Apple", "Mango", "Orange" };

        QuickSort(arr, 0, arr.Length - 1);

        Console.WriteLine("Sorted string array:");

        foreach (string str in arr)
            Console.Write(str + " ");

        Console.WriteLine();

    }

}

This demonstrates that Quick Sort is not limited to numbers. Beginners can sort words, names, or any comparable data using the same logic.

Program 4: Quick Sort With Floating-Point Numbers

Quick Sort can handle decimal numbers, which is useful in financial and scientific applications.

using System;

class Program
{

    static int Partition(double[] arr, int low, int high)
    {

        double pivot = arr[high];
        int i = low - 1;

        for (int j = low; j < high; j++)
        {

            if (arr[j] <= pivot)
            {

                i++;

                double temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;

            }

        }

        double temp1 = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp1;

        return i + 1;

    }

    static void QuickSort(double[] arr, int low, int high)
    {

        if (low < high)
        {

            int pi = Partition(arr, low, high);

            QuickSort(arr, low, pi - 1);
            QuickSort(arr, pi + 1, high);

        }

    }

    static void Main()
    {

        double[] arr = { 12.5, 3.7, 7.9, 1.2, 9.8 };

        QuickSort(arr, 0, arr.Length - 1);

        Console.WriteLine("Sorted double array:");

        foreach (double num in arr)
            Console.Write(num + " ");

        Console.WriteLine();

    }

}

This example shows that Quick Sort is versatile and can sort any comparable type, including integers, decimals, or strings.

Frequently Asked Questions (FAQ)

Q1: What is Quick Sort?
Quick Sort is a divide-and-conquer sorting algorithm that partitions arrays around a pivot element and sorts subarrays recursively.

Q2: Why is Quick Sort efficient?
It has an average time complexity of O(n log n), which is much faster than simple algorithms like Bubble or Insertion Sort for large datasets.

Q3: Can Quick Sort be used on strings or decimals?
Yes. Any type that can be compared, including strings, integers, and floating-point numbers, can be sorted using Quick Sort.

Q4: Is Quick Sort always faster than Merge Sort?
Quick Sort is usually faster in practice, but its worst-case time complexity is O(n²). Choosing a good pivot reduces the chances of worst-case performance.

Q5: Do I need extra memory for Quick Sort?
Quick Sort is in-place, meaning it sorts without additional arrays, unlike Merge Sort. This makes it memory-efficient.

Conclusion

Quick Sort is a fast and flexible algorithm that every beginner C# programmer should learn. By working with integers, decimals, and strings, beginners gain confidence in handling different data types and applying recursion effectively. Practicing Quick Sort with predefined arrays allows learners to visualize the partitioning and sorting process, making it easier to grasp. Mastering Quick Sort provides a strong foundation for exploring more advanced algorithms and improving problem-solving skills in real-world programming projects.

Scroll to Top