This is similar to Median Sort, which I skipped, but Quicksort supersedes it. This uses a similar strategy, but instead of finding the median, it accepts any value for the pivot index, then simply performs an insertion sort on the resulting partitioned array of 2 sub-arrays. The insertion sort used here is from a prior post on Insertion Sort.
Class
using System;
namespace Algorithms
{
class QuickSort
{
public void Sort()
{
//creates array
int[] arrayToSort = { 11, 1, 22, 2, 33, 3, 44, 4, 55, 5, 66, 6, 7, 77 };
//gets pivotIndex, set at midpoint of arry
int pivotIndex = Partition(arrayToSort, 0, arrayToSort.Length - 1, (arrayToSort.Length - 1)/2);
//sorts each ~half array
arrayToSort = InsertionSort.Sort(arrayToSort, 0, pivotIndex);
arrayToSort = InsertionSort.Sort(arrayToSort, pivotIndex, arrayToSort.Length - 1);
}
public int Partition(int[] arrayToSort, int startIndex, int endIndex, int pivotIndex)
{
//swap pivot index with end index
int lastValue = arrayToSort[endIndex];
int pivotValue = arrayToSort[pivotIndex];
arrayToSort[pivotIndex] = lastValue;
arrayToSort[endIndex] = pivotValue;
////then start with arr[0]
////move right
////find first value less than value put at arr[end]
////move that value into arr[0] and move arr[0] into arr[?] of value found
////find next value less than arr[end]
int moveTo = startIndex;
for (int counter = startIndex; counter <= endIndex; counter++)
{
int temp = arrayToSort[counter];
if (temp < arrayToSort[endIndex])
{
arrayToSort[counter] = arrayToSort[moveTo];
arrayToSort[moveTo] = temp;
moveTo += 1;
}
}
int tmp = arrayToSort[endIndex];
arrayToSort[endIndex] = arrayToSort[moveTo];
arrayToSort[moveTo] = tmp;
//returns pivot index (index of partition value)
return moveTo;
}
}
}
Comments
Post a Comment