Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created August 30, 2021 16:35
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save parzibyte/eba38287c28974cd634f1c34554f6fe7 to your computer and use it in GitHub Desktop.
using System;
namespace ConsoleApp1
{
class Program
{
static void quicksort(int[] arreglo, int izquierda, int derecha)
{
if (izquierda < derecha)
{
int indiceParticion = particion(arreglo, izquierda, derecha);
quicksort(arreglo, izquierda, indiceParticion);
quicksort(arreglo, indiceParticion + 1, derecha);
}
}
static int particion(int[] arreglo, int izquierda, int derecha)
{
int pivote = arreglo[izquierda];
while (true)
{
/*
Acercar los extremos hacia el centro mientras se encuentren elementos ordenados
*/
while (arreglo[izquierda] < pivote)
{
izquierda++;
}
while (arreglo[derecha] > pivote)
{
derecha--;
}
// Si los extremos se cruzaron o superaron, entonces toda la porción del arreglo estaba ordenada
if (izquierda >= derecha)
{
// Regresamos el índice para indicar hasta qué posición el arreglo está en orden
return derecha;
}
else
{
// Si no estuvieron ordenados, vamos a hacer el intercambio
int temporal = arreglo[izquierda];
arreglo[izquierda] = arreglo[derecha];
arreglo[derecha] = temporal;
// Y acercamos en 1 los extremos
derecha--; izquierda++;
}
// El while se repite hasta que izquierda >= derecha
}
}
static void Main(string[] args)
{
/*
https://parzibyte.me/blog
*/
int[] arreglo = { 45, 12, 40, 34, 5, 10, 14, 900, 888, 700, 600, 4000, 1200 };
Console.WriteLine("Antes de ordenar: ");
foreach (int elemento in arreglo)
{
Console.Write(elemento);
Console.Write(",");
}
// Ordenar. Recuerda que el arreglo original será modificado
quicksort(arreglo, 0, arreglo.Length - 1);
Console.WriteLine("\nDespués de ordenar: ");
foreach (int elemento in arreglo)
{
Console.Write(elemento);
Console.Write(",");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment