Нестандартная быстрая сортировка (без рекурсии) - C#
Формулировка задачи:
Помогите пожалуйста, нужно написать программу для одномерного массива, с помощью быстрой сотрировки без рекурсии. Если можно с комментариями! Заранее спасибо! Если можно в MS Visual studio сразу!
Решение задачи: «Нестандартная быстрая сортировка (без рекурсии)»
textual
Листинг программы
using System.Collections.Generic;
namespace ConsoleApplication28
{
class Program
{
static void
Main ( string[] args )
{
var t = new int[] { 65465, 664489, 21, 3, 48, 989, 4, 8, 6, 535, 865, 6, 95, 472, 5456, 686 };
q_sort( t );
return;
}
static void q_sort ( int[] input )
{
var stack = new Stack<int>();
int pivot;
int pivotIndex = 0;
int leftIndex = pivotIndex + 1;
int rightIndex = input.Length - 1;
stack.Push( pivotIndex );//Push always with left and right
stack.Push( rightIndex );
int leftIndexOfSubSet, rightIndexOfSubset;
while ( stack.Count > 0 )
{
rightIndexOfSubset = stack.Pop();//pop always with right and left
leftIndexOfSubSet = stack.Pop();
leftIndex = leftIndexOfSubSet + 1;
pivotIndex = leftIndexOfSubSet;
rightIndex = rightIndexOfSubset;
pivot = input[pivotIndex];
if ( leftIndex > rightIndex )
continue;
while ( leftIndex < rightIndex )
{
while ( (leftIndex <= rightIndex) && (input[leftIndex] <= pivot) )
leftIndex++; //increment right to find the greater
//element than the pivot
while ( (leftIndex <= rightIndex) && (input[rightIndex] >= pivot) )
rightIndex--;//decrement right to find the
//smaller element than the pivot
if ( rightIndex >= leftIndex ) //if right index is
//greater then only swap
SwapElement( input, leftIndex, rightIndex );
}
if ( pivotIndex <= rightIndex )
if ( input[pivotIndex] > input[rightIndex] )
SwapElement( input, pivotIndex, rightIndex );
if ( leftIndexOfSubSet < rightIndex )
{
stack.Push( leftIndexOfSubSet );
stack.Push( rightIndex - 1 );
}
if ( rightIndexOfSubset > rightIndex )
{
stack.Push( rightIndex + 1 );
stack.Push( rightIndexOfSubset );
}
}
}
static void SwapElement ( int[] arr, int left, int right )
{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
}
}