Quick Sort:
It is a divide and conquer algorithm which relies on a partition operation, i.e., to partition an array, choose an element called a pivot, move all smaller elements before the pivot, and move all greater elements after it. This can be done efficiently in linear time and in-place. Later, recursively sort the lesser and greater sublists.
It is a divide and conquer algorithm which relies on a partition operation, i.e., to partition an array, choose an element called a pivot, move all smaller elements before the pivot, and move all greater elements after it. This can be done efficiently in linear time and in-place. Later, recursively sort the lesser and greater sublists.
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace DataStructureAlgoriths
{
class Sort
public void Quicksort()
{
long[] inputArray = new long[] { 4, 9, 8, 6, 3, 2, 1 };
int left = 0;
int right = inputArray.Length - 1;
long[] final = InternalQuickSort(inputArray, left, right);
foreach (var item in final)
{
Console.WriteLine(item);
}
}
private long[] InternalQuickSort(long[] inputArray, int left, int right)
{
int pivotNewIndex = Partition(inputArray, left, right);
long pivot = inputArray[(left + right) / 2];
if (left < pivotNewIndex - 1)
InternalQuickSort(inputArray,
left, pivotNewIndex - 1);
if (pivotNewIndex < right)
InternalQuickSort(inputArray,
pivotNewIndex, right);
return inputArray;
}
private int Partition(long[] inputArray, int left, int right)
{
int i = left, j = right;
long pivot = inputArray[(left + right) / 2];
while (i <= j)
{
while (inputArray[i] < pivot)
i++;
while (inputArray[j] > pivot)
j--;
if (i <= j)
{
SwapWithTemp(ref inputArray[i], ref inputArray[j]);
i++; j--;
}
}
return i;
}
private void SwapWithTemp(ref long valOne, ref long valTwo)
{
long temp = valOne;
valOne = valTwo;
valTwo = temp;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace DataStructureAlgoriths
{
class Program
{
static void Main(string[] args)
{
Sort s = new Sort();
s.Quicksort();
Console.ReadLine();
}
}
}
No comments:
Post a Comment