How it Works:-
The algorithm starts by choosing a pivot value. It proceeds by partitioning the elements. Elements larger than the pivot are partitioned on the right side of the pivot and element smaller than the pivot are partitioned on the left side of the pivot. It then recursively applies the algorithm on the partitions.Below I have written a quick short program in c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleDemoApp
{
class test
{
static void Main(string[] args)
{
Console.Write("\nQUICK SORT Program in using Recursive Method c#");
Console.Write("\n\nEnter the total number of elements: ");
int max = Convert.ToInt32(Console.ReadLine());
int[] NumArray = new int[max];
for (int i = 0; i < max; i++)
{
Console.Write("\nEnter [" + (i + 1).ToString() + "] element: ");
NumArray[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nBefore Sorting : ");
for (int k = 0; k < max; k++)
Console.Write(NumArray[k] + " ");
Console.Write("\n");
QuickSort_Recursive(NumArray, 0, max - 1);
Console.Write("\nShorted Array : ");
for (int k = 0; k < max; k++)
Console.Write(NumArray[k] + " ");
Console.WriteLine("\nPress any key to continue");
Console.ReadLine();
}
static public int Partition(int[] numbers, int left, int right)
{
int pivot = numbers[left];
while (true)
{
while (numbers[left] < pivot)
left++;
while (numbers[right] > pivot)
right--;
if (left < right)
{
int temp = numbers[right];
numbers[right] = numbers[left];
numbers[left] = temp;
}
else
{
return right;
}
}
}
static public void QuickSort_Recursive(int[] arr, int left, int right)
{
// For Recusrion
if (left < right)
{
int pivot = Partition(arr, left, right);
if (pivot > 1)
QuickSort_Recursive(arr, left, pivot - 1);
if (pivot + 1 < right)
QuickSort_Recursive(arr, pivot + 1, right);
}
}
}
}
No comments:
Post a Comment