Created
June 28, 2012 02:17
-
-
Save categulario/3008341 to your computer and use it in GitHub Desktop.
Aplicando el algoritmo quicksort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Este programa lee un numero entero positivo n y llena un arreglo | |
* con n elementos para luego ordenarlos usando el algoritmo quicksort | |
*/ | |
#include<iostream> | |
using namespace std; | |
void quicksort(int arreglo[], int inicio, int fin){ | |
if(fin-inicio <= 0){ | |
return; | |
} | |
if(fin-inicio == 1){ | |
if(arreglo[inicio] > arreglo[fin]){ | |
int aux = arreglo[inicio]; | |
arreglo[inicio] = arreglo[fin]; | |
arreglo[fin] = aux; | |
} | |
return; | |
} | |
//Se usa como pivote el primer elemento | |
int i = inicio+1, j=fin; | |
do{ | |
while(arreglo[i]<arreglo[inicio]) | |
i++; | |
while(arreglo[j]>arreglo[inicio]) | |
j--; | |
if(i<j){ | |
int aux = arreglo[i]; | |
arreglo[i] = arreglo[j]; | |
arreglo[j] = aux; | |
} | |
}while(i<j); | |
if(arreglo[j]<arreglo[inicio]){ | |
int aux = arreglo[j]; | |
arreglo[j] = arreglo[inicio]; | |
arreglo[inicio] = aux; | |
} | |
quicksort(arreglo, inicio, j-1); | |
quicksort(arreglo, j+1, fin); | |
} | |
int main(){ | |
int n; | |
int *array; | |
cin >> n; | |
array = new int[n]; | |
for(int i=0;i<n;i++){ | |
cin >> array[i]; | |
} | |
cout << "El arreglo es de tamaño " << n << endl; | |
quicksort(array, 0, n-1); //Llamamos a la funcion | |
cout << "El arreglo ordenado es:" << endl; | |
for(int j=0;j<n;j++){ | |
cout << array[j] << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment