SlideShare una empresa de Scribd logo
PROYECTO #4 ORDENAMIENTO RAPIDO (QUICKSORT) PARA ARREGLOS
INTRODUCCION El ordenamiento rápido (quicksort en inglés) es un algoritmo basado en la técnica de divide y vencerás, que permite, en promedio, ordenar n elementos en un tiempo proporcional a n log n. El algoritmo fundamental es el siguiente: Elegir un elemento de la lista de elementos a ordenar, al que llamaremos pivote. Resituar los demás elementos de la lista a cada lado del pivote, de manera que a un lado queden todos los menores que él, y al otro los mayores. Los elementos iguales al pivote pueden ser colocados tanto a su derecha como a su izquierda, dependiendo de la implementación deseada. En este momento, el pivote ocupa exactamente el lugar que le corresponderá en la lista ordenada. La lista queda separada en dos sublistas, una formada por los elementos a la izquierda del pivote, y otra por los elementos a su derecha. Repetir este proceso de forma recursiva para cada sublista mientras éstas contengan más de un elemento. Una vez terminado este proceso todos los elementos estarán ordenados. Como se puede suponer, la eficiencia del algoritmo depende de la posición en la que termine el pivote elegido.
EJEMPLO PASO A PASO En el siguiente ejemplo se marcan el pivote y los índices i y j con las letras p, i y j respectivamente. Comenzamos con la lista completa. El elemento divisor será el 4: 5 - 3 - 7 - 6 - 2 - 1 – 4                                p  Comparamos con el 5 por la izquierda y el 1 por la derecha. 5 - 3 - 7 - 6 - 2 - 1 – 4  i                        j     p  5 es mayor que 4 y 1 es menor. Intercambiamos: 1 - 3 - 7 - 6 - 2 - 5 – 4  i                        j     p  Avanzamos por la izquierda y la derecha: 1 - 3 - 7 - 6 - 2 - 5 - 4        i              j         p
 3 es menor que 4: avanzamos por la izquierda. 2 es menor que 4: nos mantenemos ahí. 1 - 3 - 7 - 6 - 2 - 5 – 4           i          j         p         7 es mayor que 4 y 2 es menor: intercambiamos. 1 - 3 - 2 - 6 - 7 - 5 - 4             i         j         p  Avanzamos por ambos lados: 1 - 3 - 2 - 6 - 7 - 5 – 4 iyj              p  En este momento termina el ciclo principal, porque los índices se cruzaron. Ahora intercambiamos lista[i] con lista[sup] (pasos 16-18): 1 - 3 - 2 - 4 - 7 - 5 - 6                  P  Aplicamos recursivamente a la sublista de la izquierda (índices 0 - 2). Tenemos lo siguiente: 1 - 3 - 2  1 es menor que 2: avanzamos por la izquierda. 3 es mayor: avanzamos por la derecha. Como se intercambiaron los índices termina el ciclo. Se intercambia lista[i] con lista[sup]: 1 - 2 – 3  El mismo procedimiento se aplicará a la otra sublista. Al finalizar y unir todas las sublistas queda la lista inicial ordenada en forma ascendente. 1 - 2 - 3 - 4 - 5 - 6 - 7
pseudocódigo
Pseudocódigo inicio  	variables A: arreglo[1..100] entero  	variables i,j,central:entero 	variables primero, ultimo: entero  	para i = 1 hasta 100  			leer(A[i])  		Fin para  	primero = 1  	ultimo = 100  qsort(A[],100)  Fin  Funcionqsort(primero, ultimo:entero) 		 i = primero 		 j = ultimo 		 central = A[(primero,ultimo) div 2] 		 repetir  			mientras A[i]central 				 j = j - 1  			fin mientras  			si i < = j  aux = A[i] 	 			A[j] = A[i]  				A[i] = aux 				i = i + 1  				j = j – 1  			fin si  		hasta que i > j  	si primero < j 		 partir(primero,j)  	fin si  	si i < ultimo  		partir(i, ultimo) 	 fin si  fin funcionqsort
Diagrama de flujo
Algoritmos

Más contenido relacionado

Último

Presentacion de Estado del Arte del The Clean
Presentacion de Estado del Arte del The CleanPresentacion de Estado del Arte del The Clean
Presentacion de Estado del Arte del The Clean
juanchogame18
 
Nuevos tiempos, nuevos espacios.docxdsdsad
Nuevos tiempos, nuevos espacios.docxdsdsadNuevos tiempos, nuevos espacios.docxdsdsad
Nuevos tiempos, nuevos espacios.docxdsdsad
larapalaciosmonzon28
 
Catalogo general Ariston Amado Salvador distribuidor oficial Valencia
Catalogo general Ariston Amado Salvador distribuidor oficial ValenciaCatalogo general Ariston Amado Salvador distribuidor oficial Valencia
Catalogo general Ariston Amado Salvador distribuidor oficial Valencia
AMADO SALVADOR
 
Informació Projecte Iniciativa TIC HPE.pdf
Informació Projecte Iniciativa TIC HPE.pdfInformació Projecte Iniciativa TIC HPE.pdf
Informació Projecte Iniciativa TIC HPE.pdf
Festibity
 
TECLADO ERGONÓMICO Y PANTALLAS TACTILES - GESTIÓN INTEGRAL EDUCATIVA
TECLADO ERGONÓMICO Y PANTALLAS TACTILES - GESTIÓN INTEGRAL EDUCATIVATECLADO ERGONÓMICO Y PANTALLAS TACTILES - GESTIÓN INTEGRAL EDUCATIVA
TECLADO ERGONÓMICO Y PANTALLAS TACTILES - GESTIÓN INTEGRAL EDUCATIVA
LilibethEstupian
 
Computacion cuántica y sus ventajas y desventajas
Computacion cuántica y sus ventajas y desventajasComputacion cuántica y sus ventajas y desventajas
Computacion cuántica y sus ventajas y desventajas
sofiahuarancabellido
 
Actividad Conceptos básicos de programación.pdf
Actividad Conceptos básicos de programación.pdfActividad Conceptos básicos de programación.pdf
Actividad Conceptos básicos de programación.pdf
NajwaNimri1
 
Catalogo General Electrodomesticos Teka Distribuidor Oficial Amado Salvador V...
Catalogo General Electrodomesticos Teka Distribuidor Oficial Amado Salvador V...Catalogo General Electrodomesticos Teka Distribuidor Oficial Amado Salvador V...
Catalogo General Electrodomesticos Teka Distribuidor Oficial Amado Salvador V...
AMADO SALVADOR
 
Manual de Soporte y mantenimiento de equipo de cómputos
Manual de Soporte y mantenimiento de equipo de cómputosManual de Soporte y mantenimiento de equipo de cómputos
Manual de Soporte y mantenimiento de equipo de cómputos
cbtechchihuahua
 
Sitios web 3.0 funciones ventajas y desventajas
Sitios web 3.0 funciones ventajas y desventajasSitios web 3.0 funciones ventajas y desventajas
Sitios web 3.0 funciones ventajas y desventajas
paulroyal74
 
TODO SOBRE LA INFORMÁTICA, HISTORIA, ¿QUE ES?, IMPORTANCIA Y CARACTERISTICAS....
TODO SOBRE LA INFORMÁTICA, HISTORIA, ¿QUE ES?, IMPORTANCIA Y CARACTERISTICAS....TODO SOBRE LA INFORMÁTICA, HISTORIA, ¿QUE ES?, IMPORTANCIA Y CARACTERISTICAS....
TODO SOBRE LA INFORMÁTICA, HISTORIA, ¿QUE ES?, IMPORTANCIA Y CARACTERISTICAS....
bendezuperezjimena
 
modelosdeteclados-230114024527-aa2c9553.pptx
modelosdeteclados-230114024527-aa2c9553.pptxmodelosdeteclados-230114024527-aa2c9553.pptx
modelosdeteclados-230114024527-aa2c9553.pptx
evelinglilibethpeafi
 
herramientas de sitio web 3.0 2024
herramientas de sitio web 3.0  2024herramientas de sitio web 3.0  2024
herramientas de sitio web 3.0 2024
julio05042006
 
edublogs info.docx asdasfasfsawqrdqwfqwfqwfq
edublogs info.docx asdasfasfsawqrdqwfqwfqwfqedublogs info.docx asdasfasfsawqrdqwfqwfqwfq
edublogs info.docx asdasfasfsawqrdqwfqwfqwfq
larapalaciosmonzon28
 
computacion global 3.pdf pARA TERCER GRADO
computacion global 3.pdf pARA TERCER GRADOcomputacion global 3.pdf pARA TERCER GRADO
computacion global 3.pdf pARA TERCER GRADO
YaniEscobar2
 
Presentación de Tic en educación y sobre blogger
Presentación de Tic en educación y sobre bloggerPresentación de Tic en educación y sobre blogger
Presentación de Tic en educación y sobre blogger
larapalaciosmonzon28
 
Projecte Iniciativa TIC 2024 HPE. inCV.pdf
Projecte Iniciativa TIC 2024 HPE. inCV.pdfProjecte Iniciativa TIC 2024 HPE. inCV.pdf
Projecte Iniciativa TIC 2024 HPE. inCV.pdf
Festibity
 
Conceptos básicos de programación 10-5.pdf
Conceptos básicos de programación 10-5.pdfConceptos básicos de programación 10-5.pdf
Conceptos básicos de programación 10-5.pdf
ValeriaAyala48
 
Manual de soporte y mantenimiento de equipo de cómputo
Manual de soporte y mantenimiento de equipo de cómputoManual de soporte y mantenimiento de equipo de cómputo
Manual de soporte y mantenimiento de equipo de cómputo
doctorsoluciones34
 
mantenimiento de chasis y carroceria1.pptx
mantenimiento de chasis y carroceria1.pptxmantenimiento de chasis y carroceria1.pptx
mantenimiento de chasis y carroceria1.pptx
MiguelAtencio10
 

Último (20)

Presentacion de Estado del Arte del The Clean
Presentacion de Estado del Arte del The CleanPresentacion de Estado del Arte del The Clean
Presentacion de Estado del Arte del The Clean
 
Nuevos tiempos, nuevos espacios.docxdsdsad
Nuevos tiempos, nuevos espacios.docxdsdsadNuevos tiempos, nuevos espacios.docxdsdsad
Nuevos tiempos, nuevos espacios.docxdsdsad
 
Catalogo general Ariston Amado Salvador distribuidor oficial Valencia
Catalogo general Ariston Amado Salvador distribuidor oficial ValenciaCatalogo general Ariston Amado Salvador distribuidor oficial Valencia
Catalogo general Ariston Amado Salvador distribuidor oficial Valencia
 
Informació Projecte Iniciativa TIC HPE.pdf
Informació Projecte Iniciativa TIC HPE.pdfInformació Projecte Iniciativa TIC HPE.pdf
Informació Projecte Iniciativa TIC HPE.pdf
 
TECLADO ERGONÓMICO Y PANTALLAS TACTILES - GESTIÓN INTEGRAL EDUCATIVA
TECLADO ERGONÓMICO Y PANTALLAS TACTILES - GESTIÓN INTEGRAL EDUCATIVATECLADO ERGONÓMICO Y PANTALLAS TACTILES - GESTIÓN INTEGRAL EDUCATIVA
TECLADO ERGONÓMICO Y PANTALLAS TACTILES - GESTIÓN INTEGRAL EDUCATIVA
 
Computacion cuántica y sus ventajas y desventajas
Computacion cuántica y sus ventajas y desventajasComputacion cuántica y sus ventajas y desventajas
Computacion cuántica y sus ventajas y desventajas
 
Actividad Conceptos básicos de programación.pdf
Actividad Conceptos básicos de programación.pdfActividad Conceptos básicos de programación.pdf
Actividad Conceptos básicos de programación.pdf
 
Catalogo General Electrodomesticos Teka Distribuidor Oficial Amado Salvador V...
Catalogo General Electrodomesticos Teka Distribuidor Oficial Amado Salvador V...Catalogo General Electrodomesticos Teka Distribuidor Oficial Amado Salvador V...
Catalogo General Electrodomesticos Teka Distribuidor Oficial Amado Salvador V...
 
Manual de Soporte y mantenimiento de equipo de cómputos
Manual de Soporte y mantenimiento de equipo de cómputosManual de Soporte y mantenimiento de equipo de cómputos
Manual de Soporte y mantenimiento de equipo de cómputos
 
Sitios web 3.0 funciones ventajas y desventajas
Sitios web 3.0 funciones ventajas y desventajasSitios web 3.0 funciones ventajas y desventajas
Sitios web 3.0 funciones ventajas y desventajas
 
TODO SOBRE LA INFORMÁTICA, HISTORIA, ¿QUE ES?, IMPORTANCIA Y CARACTERISTICAS....
TODO SOBRE LA INFORMÁTICA, HISTORIA, ¿QUE ES?, IMPORTANCIA Y CARACTERISTICAS....TODO SOBRE LA INFORMÁTICA, HISTORIA, ¿QUE ES?, IMPORTANCIA Y CARACTERISTICAS....
TODO SOBRE LA INFORMÁTICA, HISTORIA, ¿QUE ES?, IMPORTANCIA Y CARACTERISTICAS....
 
modelosdeteclados-230114024527-aa2c9553.pptx
modelosdeteclados-230114024527-aa2c9553.pptxmodelosdeteclados-230114024527-aa2c9553.pptx
modelosdeteclados-230114024527-aa2c9553.pptx
 
herramientas de sitio web 3.0 2024
herramientas de sitio web 3.0  2024herramientas de sitio web 3.0  2024
herramientas de sitio web 3.0 2024
 
edublogs info.docx asdasfasfsawqrdqwfqwfqwfq
edublogs info.docx asdasfasfsawqrdqwfqwfqwfqedublogs info.docx asdasfasfsawqrdqwfqwfqwfq
edublogs info.docx asdasfasfsawqrdqwfqwfqwfq
 
computacion global 3.pdf pARA TERCER GRADO
computacion global 3.pdf pARA TERCER GRADOcomputacion global 3.pdf pARA TERCER GRADO
computacion global 3.pdf pARA TERCER GRADO
 
Presentación de Tic en educación y sobre blogger
Presentación de Tic en educación y sobre bloggerPresentación de Tic en educación y sobre blogger
Presentación de Tic en educación y sobre blogger
 
Projecte Iniciativa TIC 2024 HPE. inCV.pdf
Projecte Iniciativa TIC 2024 HPE. inCV.pdfProjecte Iniciativa TIC 2024 HPE. inCV.pdf
Projecte Iniciativa TIC 2024 HPE. inCV.pdf
 
Conceptos básicos de programación 10-5.pdf
Conceptos básicos de programación 10-5.pdfConceptos básicos de programación 10-5.pdf
Conceptos básicos de programación 10-5.pdf
 
Manual de soporte y mantenimiento de equipo de cómputo
Manual de soporte y mantenimiento de equipo de cómputoManual de soporte y mantenimiento de equipo de cómputo
Manual de soporte y mantenimiento de equipo de cómputo
 
mantenimiento de chasis y carroceria1.pptx
mantenimiento de chasis y carroceria1.pptxmantenimiento de chasis y carroceria1.pptx
mantenimiento de chasis y carroceria1.pptx
 

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
Marius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
Expeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
marketingartwork
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
Skeleton Technologies
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
SpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Lily Ray
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
Christy Abraham Joy
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
Vit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
MindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Algoritmos

  • 1. PROYECTO #4 ORDENAMIENTO RAPIDO (QUICKSORT) PARA ARREGLOS
  • 2. INTRODUCCION El ordenamiento rápido (quicksort en inglés) es un algoritmo basado en la técnica de divide y vencerás, que permite, en promedio, ordenar n elementos en un tiempo proporcional a n log n. El algoritmo fundamental es el siguiente: Elegir un elemento de la lista de elementos a ordenar, al que llamaremos pivote. Resituar los demás elementos de la lista a cada lado del pivote, de manera que a un lado queden todos los menores que él, y al otro los mayores. Los elementos iguales al pivote pueden ser colocados tanto a su derecha como a su izquierda, dependiendo de la implementación deseada. En este momento, el pivote ocupa exactamente el lugar que le corresponderá en la lista ordenada. La lista queda separada en dos sublistas, una formada por los elementos a la izquierda del pivote, y otra por los elementos a su derecha. Repetir este proceso de forma recursiva para cada sublista mientras éstas contengan más de un elemento. Una vez terminado este proceso todos los elementos estarán ordenados. Como se puede suponer, la eficiencia del algoritmo depende de la posición en la que termine el pivote elegido.
  • 3. EJEMPLO PASO A PASO En el siguiente ejemplo se marcan el pivote y los índices i y j con las letras p, i y j respectivamente. Comenzamos con la lista completa. El elemento divisor será el 4: 5 - 3 - 7 - 6 - 2 - 1 – 4 p Comparamos con el 5 por la izquierda y el 1 por la derecha. 5 - 3 - 7 - 6 - 2 - 1 – 4 i j p 5 es mayor que 4 y 1 es menor. Intercambiamos: 1 - 3 - 7 - 6 - 2 - 5 – 4 i j p Avanzamos por la izquierda y la derecha: 1 - 3 - 7 - 6 - 2 - 5 - 4 i j p
  • 4. 3 es menor que 4: avanzamos por la izquierda. 2 es menor que 4: nos mantenemos ahí. 1 - 3 - 7 - 6 - 2 - 5 – 4 i j p 7 es mayor que 4 y 2 es menor: intercambiamos. 1 - 3 - 2 - 6 - 7 - 5 - 4 i j p Avanzamos por ambos lados: 1 - 3 - 2 - 6 - 7 - 5 – 4 iyj p En este momento termina el ciclo principal, porque los índices se cruzaron. Ahora intercambiamos lista[i] con lista[sup] (pasos 16-18): 1 - 3 - 2 - 4 - 7 - 5 - 6 P Aplicamos recursivamente a la sublista de la izquierda (índices 0 - 2). Tenemos lo siguiente: 1 - 3 - 2 1 es menor que 2: avanzamos por la izquierda. 3 es mayor: avanzamos por la derecha. Como se intercambiaron los índices termina el ciclo. Se intercambia lista[i] con lista[sup]: 1 - 2 – 3 El mismo procedimiento se aplicará a la otra sublista. Al finalizar y unir todas las sublistas queda la lista inicial ordenada en forma ascendente. 1 - 2 - 3 - 4 - 5 - 6 - 7
  • 6. Pseudocódigo inicio variables A: arreglo[1..100] entero variables i,j,central:entero variables primero, ultimo: entero para i = 1 hasta 100 leer(A[i]) Fin para primero = 1 ultimo = 100 qsort(A[],100) Fin Funcionqsort(primero, ultimo:entero) i = primero j = ultimo central = A[(primero,ultimo) div 2] repetir mientras A[i]central j = j - 1 fin mientras si i < = j aux = A[i] A[j] = A[i] A[i] = aux i = i + 1 j = j – 1 fin si hasta que i > j si primero < j partir(primero,j) fin si si i < ultimo partir(i, ultimo) fin si fin funcionqsort