Sei sulla pagina 1di 2

using System;

using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public void quicksort(int[] input, int low, int high)
{
int[] pivot_loc = new int[2];
if (low < high)
{
pivot_loc = partition(input, low, high);
quicksort(input, low, pivot_loc[0] - 1);
quicksort(input, pivot_loc[1] + 1, high);
}
}
private int[] partition(int[] input, int low, int high)
{
int[] pivot_loc = new int[2];
int pivot = input[high];
int i = low;
int k = high;
for (int j = low; j < k; j++)
{
if (input[j] < pivot)
{ swap(input, i, j); i++; }
else if (input[j] == pivot)
{ swap(input, j, k - 1); k--; j--; }
}
int m;
if ((k - 1) < (high - k + 1))
{ m = k - i; }
else
{
m = high - k + 1;
}
for (int p = 0; p < m; p++)
{
swap(input, i + p, high - m + 1 + p);
}
pivot_loc[0] = i;
pivot_loc[1] = i + high - k;
return pivot_loc;
}
private void swap(int[] array, int a, int b)
{
int temp;
temp = array[a];
array[a] = array[b];
array[b] = temp;
}
static void Main(string[] args)
{
Program prog = new Program();
Console.Write("Koliko zelite elemenata? ");
int n = Convert.ToInt32(Console.ReadLine());
int[] niz = new int[n];
for (int i = 0; i < n; i++)
{
Console.Write("Unesite element " + (i+1).ToString() + ": ");
niz[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine();
Console.Write("Nesredjen niz: ");
for (int i = 0; i < n; i++)
{
if (i < n - 1)
{
Console.Write(niz[i].ToString() + " ");
}
else
{
Console.WriteLine(niz[i].ToString());
}
}
prog.quicksort(niz, 0, n - 1);
Console.WriteLine();
Console.Write("Sredjen niz : ");
for (int i = 0; i < n; i++)
{
if (i < n - 1)
{
Console.Write(niz[i].ToString() + " ");
}
else
{
Console.WriteLine(niz[i].ToString());
}
}
Console.WriteLine();
Console.Write("Stisnite ENTER za kraj: ");
Console.ReadLine();
}
}
}

Potrebbero piacerti anche