DUTCH NATIONAL FLAG SORTING (DNF SORTING)
namespace DutchFlagAlgo
{
class Program
{
public static void dutchFlagSort(int[] arr, int p, int k)
{
int p_index = 0;
int k_index = arr.Length - 1;
for (int i = 0; i <= k_index; )
{
if (arr[i] < p)
{
swap(arr, i, p_index);
p_index++;
i++;
}
else if (arr[i] >= k)
{
swap(arr, i, k_index);
k_index--;
}
else
{
i++;
}
}
}
public static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void Main(string[] args)
{
int[] arr = { 3,5,4,2,1};
dutchFlagSort(arr, 2, 4);
foreach (int a in arr) Console.Write(a+" ");
}
}
}
No comments:
Post a Comment