Quicksort elige un pivote, divide los valores alrededor de él y repite el proceso en cada lado. Aquí siempre se elige el primer valor. Si las partes quedan equilibradas, el tiempo es Θ(n log n). Si el pivote es siempre el menor o el mayor, el tiempo sube a Θ(n²). Con esta regla pasa también cuando los datos ya están ordenados.
Ejemplo sencillo
Elija 2 como el pivote. Mueva 1 a su izquierda y 3 a su derecha. Cada lado ahora tiene un elemento.
Al empezar3 1 2
Resultado1 2 3
Main.java
public class Main {
public static void main(String[] args) {
int[] values = {3, 1, 2};
int pivot = values[2];
int boundary = 0;
int i = 0;
while (i < 2) {
if (values[i] < pivot) {
int saved = values[i];
values[i] = values[boundary];
values[boundary] = saved;
boundary += 1;
}
i += 1;
}
values[2] = values[boundary];
values[boundary] = pivot;
i = 0;
while (i < 3) {
System.out.println(values[i]);
i += 1;
}
}
}
Salida
1
2
3
Ejemplos de la vida diaria
Separar paquetes según un peso de referencia
Tres paquetes pesan 8, 2 y 5 kilos. Toma 5 como peso de referencia. ¿Qué paquete queda a cada lado?
Al empezar8 2 5
Resultado2 • 5 • 8
Dos es más ligero y ocho es más pesado. El pivote ahora separa a los dos grupos.
Tratar libros con el mismo precio
Cada libro cuesta 4. ¿Qué produciría una partición de tres vías?
Al empezar4 4 4
Resultado∅ • 4 4 4 • ∅
El grupo igual contiene cada libro. Ninguno de los grupos externos necesita más trabajo.
Reconocer un pivote mal elegido
Fechas 1, 2, 3 y 4 están en orden. Elige siempre la última cita. ¿Qué pasa en la primera división?
Al empezar1 2 3 4
Resultado1 2 3 • 4 • ∅
Un grupo todavía tiene tres artículos. Repetir estas comparaciones de residuos de patrón.
Coste y límites
Particiones equilibradas suelen llevar a un trabajo de O(n log n). Elijer repetidamente un pivote extremo puede llevar a O(n²).
Complejidad temporal
Mejor caso: Θ(n log n)
Caso promedio: Θ(n log n)
Peor caso: Θ(n²)
Ordenación rápida en Java
Código fuente en Java
class QuickSortExample {
public void quickSort(int[] arr, int low, int high) {
if(low < high) {
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}
private int partition(int[] arr, int low, int high) {
int pivot = arr[low];
int i = low;
int j = high;
while(i < j) {
while(arr[i] <= pivot && i < high) {
i++;
}
while(arr[j] > pivot && j > low) {
j--;
}
if(i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
arr[low] = arr[j];
arr[j] = pivot;
return j;
}
public void printArray(int[] arr) {
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
QuickSortExample obj = new QuickSortExample();
int[] arr = { 15, 3, 12, 6, -9, 9, 0 };
System.out.print("Before Sorting: ");
obj.printArray(arr);
obj.quickSort(arr, 0, arr.length - 1);
System.out.print("After Sorting: ");
obj.printArray(arr);
}
}
Salida
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Anuncios
Sigue el ejemplo paso a paso
Empieza con [15, 3, 12, 6, -9, 9, 0].
Utilice el primer valor, 15, como el pivote. Escanear hacia adentro desde ambos extremos.
Mueve el índice izquierdo hacia la derecha mientras el valor que señala sea menor o igual que el pivote y el índice no haya llegado al límite superior. Mueve el índice derecho hacia la izquierda mientras su valor sea mayor que el pivote.
Si los índices no se han encontrado, intercambia los dos valores in situ y continúa escaneando.
Cuando los índices se reúnen o cruzan, intercambian el primer valor con el valor en el índice adecuado. El pivote está ahora en su posición final.
Recursively ordenar los rangos antes y después de esa posición. Un rango con menos de dos elementos ya está clasificado.
Ordenación rápida en Java paso a paso
Código fuente en Java
class QuickSortExample {
public void quickSort(int[] arr, int low, int high) {
if(low < high) {
// Find the pivot index of the lower bound of an array
int pivot = partition(arr, low, high);
// Apply Divide and conquer strategy
// to sort the left side and right side of an array
// respective to the pivot position
// Left hand side array
quickSort(arr, low, pivot - 1);
// Right hand side array
quickSort(arr, pivot + 1, high);
}
}
private int partition(int[] arr, int low, int high) {
// Pick a lowest bound element as an pivot value
int pivot = arr[low];
int i = low;
int j = high;
while(i < j) {
// Increment the index value of "i"
// till the left most values should be less than or equal to the pivot value
while(arr[i] <= pivot && i < high) {
i++;
}
// Decrement the index value of "j"
// till the right most values should be greater than to the pivot value
while(arr[j] > pivot && j > low) {
j--;
}
// Interchange the values of present
// in the index i and j of an array only if i is less than j
if(i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Interchange the element in j's poisition to the lower bound of an array
// and place the Pivot element to the j's position
arr[low] = arr[j];
arr[j] = pivot;
// Finally return the appropriate index position of the pivot element
return j;
}
public void printArray(int[] arr) {
// Loop the item and print each item in the console with white space seperated
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
QuickSortExample obj = new QuickSortExample();
int[] arr = { 15, 3, 12, 6, -9, 9, 0 };
System.out.print("Before Sorting: ");
obj.printArray(arr);
obj.quickSort(arr, 0, arr.length - 1);
System.out.print("After Sorting: ");
obj.printArray(arr);
}
}
Salida
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15