SlideShare una empresa de Scribd logo
1 de 23
Tema 8b
Búsqueda y ordenación en arreglos
Ordenación
• Es un proceso que altera el orden de los elementos
de un conjunto.
• Tiene asociada una relación de orden
– Números: valor
– Letras: alfabeto
– Auto: ¿Velocidad? ¿Tamaño? ¿Autonomía?
– Amigos: ¿…..?
• La ordenación puede ser ascendente o
descendente.
Ordenación
• Métodos
– Burbuja (Bubble sort)
– Selección
– Inserción
– Burbuja bidireccional
– Rápido (Quicksort)
Bubble sort
• Los elementos más
“pesados” “bajan”
• Los elementos más
“livianos” “suben”
• Cuando ya no puede
bajar más se sigue con
el resto.
Bubble sort
r
a
c
f
b
e
i
a
1-Como r es más “pesada” que a,
r “baja” y a “sube”
a
r
c
f
b
e
i
a
a
c
r
f
b
e
i
a
2-Como r es más “pesada” que c,
r “baja” y c “sube”
a
c
f
b
e
i
a
r
…
Bubble sort
void bubblesort(int numeros[]){
int i,j;
for(i=1;i<N;i++)
for(j=0;j<(N-i);j++)
if(numeros[j]>numeros[j+1]){
int aux = numeros[j+1];
numeros[j+1] = numeros[j];
numeros[j] = aux;
}
}
Selección
• Se selecciona el minimo valor entre los N
elementos y se intercambia con el primero.
• Se repite la operación con los N-1
elementos restantes.
Selección
void selectionsort_up(int numeros[]){
int i,j,k,r;
int n;
int inter;
for(i=0;i<N-1;i++){
inter=0;
k=i;
n=numeros[i];
for(j=i+1;j<N;j++)
if(numeros[j]<n){
r=j;
n=numeros[j];
inter=1;
}
if(inter){
numeros[r] = numeros[i];
numeros[i] = n;
}
}
}
Inserción
• Ordena el subarreglos de manera creciente
• Ordena los primeros dos elementos
• Luego va insertando los siguientes en su
posición ordenada en el subarreglo.
Inserción
void insertionsort_up(int numeros[]){
int i,j;
int n;
for(i=1;i<N;i++){
n=numeros[i];
for(j=i-1; (j>=0)&&(n<numeros[j]) ;j--)
numeros[j+1] = numeros[j];
numeros[j+1] = n;
}
}
Quicksort
• Los algoritmos anteriores ejecutan un
numero de instrucción del orden de N2
– Ordenar 10 elementos ejecuta a100
instrucciones.
– Ordenar 100 elementos ejecuta a10000
instrucciones.
– Ordenar 1000 elementos ejecuta a1000000
instrucciones.
Quicksort
Nº de elementos
Tiempo
de
ejecución
aN2
Quicksort
• Quicksort es un algoritmo de proposito
general.
• Es en la mayoria de los casos el más
eficiente.
• Tiene un orden a N log(N)
• Tiene una estructura recursiva.
Quicksort
Nº de elementos
Tiempo
de
ejecución
aNlog(N)
Búsqueda
• Consiste en buscar un elemento dentro de un
conjunto
• Requiere de una relación de igualdad
– Números: Igual valor
• ¿Cuántos decimales considerar?
– Letras: mismo símbolo
• ¿Mayusculas y minúsculas?
– Autos
• Modelo y año
• Placa patente
• Codigo chasis
• Etc…
Búsqueda
• Métodos
– Secuencial
– Binaria
Búsqueda secuencial
• Recorrer uno por uno los elementos.
• Comparar según sea el criterio.
• Se puede querer recuperar el valor o ela
posición.
• Tiene un orden aN
Búsqueda secuencial
int secuencial_search(int numeros[], int valor){
int i=0;
for(i=0;i<N;i++)
if(numeros[i]==valor) return i;
return -1;
}
Búsqueda secuencial
• En arreglos bidimensionales el algortimo es
similar.
• Se puede hacer por filas o por columas.
• Esta decision puede afectar el rendimiento
– Por lo general, preferir por filas.
Búsqueda secuencial
int bisecuencial_search(int numeros[][N], int valor){
int i,j;
for(i=0;i<N;i++)
for(j=0;j<N;j++)
if(numeros[i][j]==valor) return i*N+j;
return -1;
}
…
pos = bisecuencial_search(binumeros, 11);
if(pos>=0)
printf("bisec) numeros[%d][%d] = %dn",
pos/N,pos%N,
binumeros[pos/N][pos%N]);
Búsqueda binaria
• Muy rápida
• Requiere datos ordenados
• No sirve para recuperar la posición original.
• “Encierra” el numero búscado “achicando”
a la mitad el intervalo que parece
contenerlo.
• Tiene un orden alog2N
Búsqueda binaria
int binary_search(int numeros[], int valor){
int i,j,m;
insertionsort_up(numeros);
i=0;
j=N-1;
while(i<=j){
m=(i+j)/2;
if(valor<numeros[m]) j=m-1;
else if(valor>numeros[m]) i=m+1;
else return m;
}
return -1;
}
Fin Tema 8b
Búsqueda y ordenación en arreglos

Más contenido relacionado

Último

TECNOLOGÍA DE LA INFORMACIÓN SLIDESHARE INVESTIGACION.pdf
TECNOLOGÍA DE LA INFORMACIÓN SLIDESHARE INVESTIGACION.pdfTECNOLOGÍA DE LA INFORMACIÓN SLIDESHARE INVESTIGACION.pdf
TECNOLOGÍA DE LA INFORMACIÓN SLIDESHARE INVESTIGACION.pdf
UPSE
 
TECNOLOGIA DE LA INFORMACION Y MULTIMEDIA 15 MAYO.pptx
TECNOLOGIA DE LA INFORMACION Y MULTIMEDIA 15 MAYO.pptxTECNOLOGIA DE LA INFORMACION Y MULTIMEDIA 15 MAYO.pptx
TECNOLOGIA DE LA INFORMACION Y MULTIMEDIA 15 MAYO.pptx
UPSE
 
S07_s1-Control Acceso-Amenazas de seguridad de capa 2.pdf
S07_s1-Control Acceso-Amenazas de seguridad de capa 2.pdfS07_s1-Control Acceso-Amenazas de seguridad de capa 2.pdf
S07_s1-Control Acceso-Amenazas de seguridad de capa 2.pdf
larryluna927
 

Último (7)

TECNOLOGÍA DE LA INFORMACIÓN SLIDESHARE INVESTIGACION.pdf
TECNOLOGÍA DE LA INFORMACIÓN SLIDESHARE INVESTIGACION.pdfTECNOLOGÍA DE LA INFORMACIÓN SLIDESHARE INVESTIGACION.pdf
TECNOLOGÍA DE LA INFORMACIÓN SLIDESHARE INVESTIGACION.pdf
 
TECNOLOGIA DE LA INFORMACION Y MULTIMEDIA 15 MAYO.pptx
TECNOLOGIA DE LA INFORMACION Y MULTIMEDIA 15 MAYO.pptxTECNOLOGIA DE LA INFORMACION Y MULTIMEDIA 15 MAYO.pptx
TECNOLOGIA DE LA INFORMACION Y MULTIMEDIA 15 MAYO.pptx
 
El necesario mal del Legacy Code (Drupal Iberia 2024)
El necesario mal del Legacy Code (Drupal Iberia 2024)El necesario mal del Legacy Code (Drupal Iberia 2024)
El necesario mal del Legacy Code (Drupal Iberia 2024)
 
Especificación casos de uso del negocio
Especificación  casos de uso del negocioEspecificación  casos de uso del negocio
Especificación casos de uso del negocio
 
Modelado de Casos de uso del negocio
Modelado de  Casos  de  uso  del negocioModelado de  Casos  de  uso  del negocio
Modelado de Casos de uso del negocio
 
S07_s1-Control Acceso-Amenazas de seguridad de capa 2.pdf
S07_s1-Control Acceso-Amenazas de seguridad de capa 2.pdfS07_s1-Control Acceso-Amenazas de seguridad de capa 2.pdf
S07_s1-Control Acceso-Amenazas de seguridad de capa 2.pdf
 
contabilidad para la inflacion, contabilidad superior
contabilidad para la inflacion, contabilidad superiorcontabilidad para la inflacion, contabilidad superior
contabilidad para la inflacion, contabilidad superior
 

Destacado

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
 
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)
 

Destacado (20)

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...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 

08b-Arreglos.ppt

  • 1. Tema 8b Búsqueda y ordenación en arreglos
  • 2. Ordenación • Es un proceso que altera el orden de los elementos de un conjunto. • Tiene asociada una relación de orden – Números: valor – Letras: alfabeto – Auto: ¿Velocidad? ¿Tamaño? ¿Autonomía? – Amigos: ¿…..? • La ordenación puede ser ascendente o descendente.
  • 3. Ordenación • Métodos – Burbuja (Bubble sort) – Selección – Inserción – Burbuja bidireccional – Rápido (Quicksort)
  • 4. Bubble sort • Los elementos más “pesados” “bajan” • Los elementos más “livianos” “suben” • Cuando ya no puede bajar más se sigue con el resto.
  • 5. Bubble sort r a c f b e i a 1-Como r es más “pesada” que a, r “baja” y a “sube” a r c f b e i a a c r f b e i a 2-Como r es más “pesada” que c, r “baja” y c “sube” a c f b e i a r …
  • 6. Bubble sort void bubblesort(int numeros[]){ int i,j; for(i=1;i<N;i++) for(j=0;j<(N-i);j++) if(numeros[j]>numeros[j+1]){ int aux = numeros[j+1]; numeros[j+1] = numeros[j]; numeros[j] = aux; } }
  • 7. Selección • Se selecciona el minimo valor entre los N elementos y se intercambia con el primero. • Se repite la operación con los N-1 elementos restantes.
  • 8. Selección void selectionsort_up(int numeros[]){ int i,j,k,r; int n; int inter; for(i=0;i<N-1;i++){ inter=0; k=i; n=numeros[i]; for(j=i+1;j<N;j++) if(numeros[j]<n){ r=j; n=numeros[j]; inter=1; } if(inter){ numeros[r] = numeros[i]; numeros[i] = n; } } }
  • 9. Inserción • Ordena el subarreglos de manera creciente • Ordena los primeros dos elementos • Luego va insertando los siguientes en su posición ordenada en el subarreglo.
  • 10. Inserción void insertionsort_up(int numeros[]){ int i,j; int n; for(i=1;i<N;i++){ n=numeros[i]; for(j=i-1; (j>=0)&&(n<numeros[j]) ;j--) numeros[j+1] = numeros[j]; numeros[j+1] = n; } }
  • 11. Quicksort • Los algoritmos anteriores ejecutan un numero de instrucción del orden de N2 – Ordenar 10 elementos ejecuta a100 instrucciones. – Ordenar 100 elementos ejecuta a10000 instrucciones. – Ordenar 1000 elementos ejecuta a1000000 instrucciones.
  • 13. Quicksort • Quicksort es un algoritmo de proposito general. • Es en la mayoria de los casos el más eficiente. • Tiene un orden a N log(N) • Tiene una estructura recursiva.
  • 15. Búsqueda • Consiste en buscar un elemento dentro de un conjunto • Requiere de una relación de igualdad – Números: Igual valor • ¿Cuántos decimales considerar? – Letras: mismo símbolo • ¿Mayusculas y minúsculas? – Autos • Modelo y año • Placa patente • Codigo chasis • Etc…
  • 17. Búsqueda secuencial • Recorrer uno por uno los elementos. • Comparar según sea el criterio. • Se puede querer recuperar el valor o ela posición. • Tiene un orden aN
  • 18. Búsqueda secuencial int secuencial_search(int numeros[], int valor){ int i=0; for(i=0;i<N;i++) if(numeros[i]==valor) return i; return -1; }
  • 19. Búsqueda secuencial • En arreglos bidimensionales el algortimo es similar. • Se puede hacer por filas o por columas. • Esta decision puede afectar el rendimiento – Por lo general, preferir por filas.
  • 20. Búsqueda secuencial int bisecuencial_search(int numeros[][N], int valor){ int i,j; for(i=0;i<N;i++) for(j=0;j<N;j++) if(numeros[i][j]==valor) return i*N+j; return -1; } … pos = bisecuencial_search(binumeros, 11); if(pos>=0) printf("bisec) numeros[%d][%d] = %dn", pos/N,pos%N, binumeros[pos/N][pos%N]);
  • 21. Búsqueda binaria • Muy rápida • Requiere datos ordenados • No sirve para recuperar la posición original. • “Encierra” el numero búscado “achicando” a la mitad el intervalo que parece contenerlo. • Tiene un orden alog2N
  • 22. Búsqueda binaria int binary_search(int numeros[], int valor){ int i,j,m; insertionsort_up(numeros); i=0; j=N-1; while(i<=j){ m=(i+j)/2; if(valor<numeros[m]) j=m-1; else if(valor>numeros[m]) i=m+1; else return m; } return -1; }
  • 23. Fin Tema 8b Búsqueda y ordenación en arreglos