C# - Sort an Array Using Quick Sort

Here, we are going to learn how to sort an array using quick sort in C#? By Nidhi Last updated : March 28, 2023

Here, we will sort an integer array using quick sort.

Quick Sort

Quick Sort is the divide and conquer algorithm, here we picks an item as a pivot and then partition the array, normally we picked the middle element as a pivot.

The main process in quick sort is portioning. In the QuickSort(), we used recursion to process partitions and sort the array.

C# program to sort an array using quick sort

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.

C# Data Structure Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.