Q:

C# program to sort an array using quick sort

0

C# program to sort an array using quick sort

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to sort an integer array using quick sort is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//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();
    }
}

Output:

Sorted array:
12 13 21 32 34 42 43 77
Press any key to continue . . .

Explanation:

In the above program, we created a class Sort that contains an integer array intArray as a data member and we initialized the integer array using parameterized constructor.

Here, we implemented a method QuickSort() to sort the integer array based on QuickSort algorithm.

The Sort class also contains the Main() method, here we create an integer array and then passed to the parameterized constructor to initialized data members, then called QuickSort() method that will sort the array in the ascending order and printed the sorted array on the console screen.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now