Vous êtes sur la page 1sur 23

Contenido

Repaso de Anlisis y Diseo de Algoritmos


1. Notacin
2. Notacin
3. Notacin
4. Rank Sort
5. Rank Sort Rearrange
6. Rank Sort Revisited
7. Bubble Sort
8. Bubble Sort Revisited

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Notacin
f(n) = (g(n)) c, n0 tal que n f(n) cg(n) n n0
f(n) c g(n)

es usado para cotas inferiores: Mejor Caso.

n0
f(n) = 3n + 2

f(n) = (n)

f(n) = 10n2 + 4n + 2

f(n) = (n2)

f(n) = 6*2n + n2

f(n) = (2n)

f(n) = 9 ( 8, 363, 456)

f(n) = (1)

f(n) = 9n2 + 4n + 2

f(n) = (n), pero no exactamente

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Notacin
f(n) = (g(n)) c, n0 tal que n f(n) cg(n) n n0
c g(n)

f(n)

O es usado para cotas superiores: Peor Caso.

n0
f(n) = 3n + 2

f(n) = (n)

f(n) = 10n2 + 4n + 2

f(n) = (n2)

f(n) = 6*2n + n2

f(n) = (2n)

f(n) = 9 ( 8, 363, 456)

f(n) = (1)

f(n) = 9n2 + 4n + 2

f(n) = (n4), pero no exactamente

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Notacin
f(n) = (g(n)) f(n) es (g(n)) y f(n) es (g(n))
f(n)=c g(n)

es usado para cotas exactas:


ni mejor ni peor caso.

n0
f(n) = 3n + 2

f(n) = (n)

f(n) = 10n2 + 4n + 2

f(n) = (n2)

f(n) = 6*2n + n2

f(n) = (2n)

f(n) = 9 ( 8, 363, 456)

f(n) = (1)

f(n) = 9n2 si n es impar, y


4n + 2 si n es par.

no es (n) ni (n2)
4

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Complejidades
Valores de Varias Funciones [Sahni, 2005]

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Funciones [Sahni, 2005]

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Funciones [Sahni, 2005]


Tiempo de ejecucin
Computadora de 1,000,000,000 instrucciones/seg
[Sahni, 2005]

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Rank Sort
El rank de un elemento en una secuencia es el nmero de elementos
ms pequeos en la secuencia ms el nmero de elementos iguales
que aparecen a la izquierda del elemento en la secuencia.

Ejemplo:
a[0:8] = [3, 2, 6, 1, 9, 4, 3, 7, 1, 8]
r[0:8] = [3, 2, 6, 0, 9, 5, 4, 7, 1, 8]

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Rank Sort
template<class T>
void rank(T a[], int n, int r[])
{ // Secuencia de n elementos a[0:n-1]
// Rank de la secuencia r[0:n-1]

// inicializacin
for (int i = 0; i< n; i++)
r[i]=0;
// Comparacin de todos los pares
for (int i = 1; i < n; i++)
for (int j = 0; j < i; j++)
if (a[j] <= a[i])
r[i]++;
else
r[j]++;
}

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Rank Sort
a[0:5]

a[0:5]

1
1

2
1

3
1

4
1

3
1

5
1

1
r[0:5]

4
3

r[0:5]

10

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Complejidad [Sahni, 2005]


template<class T>
void rank(T a[], int n, int r[])
{
// Secuencia de n elementos a[0:n-1]
// Rank de la secuencia r[0:n-1]

// inicializacin
for (int i = 0; i< n; i++)
r[i]=0;

Para cada valor de i, el nmero


de elementos comparados es i.
Nmero total de comparaciones
1 + 2 + 3 + + (n1) = n(n1)/2

// Comparacin de todos los pares


for (int i = 1; i < n; i++)
for (int j = 0; j < i; j++)
if (a[j] <= a[i]) r[i]++;
else r[j]++;
}
11

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Arreglando los elementos de otra forma [Sahni, 2005]


template<class T>
void rearrange(T a[], int n, int r[])
{
// Arreglando los elementos ordenados
// usando un arreglo adicional u
// Creando arreglo adicional
T *u = new T [n];
// Moviendo al lugar correcto en u
for (int i = 0; i < n; i++)
u[r[i]] = a[i];
// Colocando en a
for (i = 0; i < n; i++)
a[i] = u[i];

El nmero de elementos
movidos durante la ejecucin
de la funcin rearrange es
2n.
El total es:
n(n 1)/2 comparaciones +
2n elementos movidos

delete [] u;
}
12

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Rank Sort Revisited


En lugar de arreglar los elementos [Sahni, 2005]
template<class T>
void rearrange(T a[], int n, int r[])
{
// En lugar de arreglar los elementos
for (int i = 0; i < n; i++)
// Obtener el elemento propio de a[i]
while (r[i] != i)
{
int t = r[i];
swap(a[i], a[t]);
swap(r[i], r[t]);
}

0 1 2 3 4 5

0 1 2 3 4 5

3 0 4 5 2 1

0 1 4 3 2 5

d a

a b e

e f

c b

d c f

5 0 4 3 2 1

0 1 2 3 4 5

a b c

e d c b

d e f

1 0 4 3 2 5

0 1 2 3 4 5

b a

a b c

e d c f

d e f

0 1 4 3 2 5
a b e d c f

13

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Complejidad
template<class T>
void rearrange(T a[], int n, int r[])
{
// En lugar de arreglar los elementos
for (int i = 0; i < n; i++)

// Obtener el elemento propio de a[i]


while (r[i] != i)
{
int t = r[i];
swap(a[i], a[t]);
swap(r[i], r[t]);
}

El nmero de cambios: de 0
hasta 2(n 1)

14

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Bubble Sort [Sahni, 2005]


template<class T>
void bubble(T a[], int n)
{
// Moviendo el elemento ms
// grande a la derecha
for (int i = 0; i < n - 1; i++)
if (a[i] > a[i+1]) swap(a[i], a[i + 1]);
}

El nmero de comparaciones entre los


pares de elementos de a son n 1.

8
15

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Bubble Sort [Sahni, 2005]


template<class T>
void bubbleSort(T a[], int n)
{
// Ordenar a[0:n - 1] usando
// bubble sort

for (int i = n; i > 1; i--)


bubble(a, i);
}

El
nmero
de
elementos
comparados es n(n 1)/2

5
5
4
3
1

6
4
3
1
3

4
3
1
4
4

3
1
5
5
5

1
6
6
6
6

8
8
8
8
8
16

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

Bubble Sort Revisited [Sahni, 2005]


template<class T>
bool bubble(T a[], int n)
{
// Mover el elemento ms grande a
// la derecha en a[0:n]
bool swapped = false;
for (int i = 0; i < n - 1; i++)
if (a[i] > a[i+1])
{
swap(a[i], a[i + 1]);
swapped = true;
}
return swapped;
}
template<class T>
void bubbleSort(T a[], int n)
{
// Terminacin temprana
for (int i = n; i > 1 && bubble(a, i); i--);
}

0
6
1
1
1

1
1
2
2
2

2
2
5
3
3

3
5
3
4
4

4
3
4
5
5

5
4
6
6
6

El peor caso: nmero de


comparaciones
n(n 1)/2
El mejor caso: nmero de
comparaciones
n1
17

Tomadas del curso Algorithms and Data Structure A and B, por Dr. Teofilo Gonzlez, Computer Science Department UCSB

4.1.2 Algoritmos de Ordenacin Bsica:


Ordenacin por Seleccin

18

// Sorting using selection sort


template <typename T>
void selection_sort(vector<T>& v) {
for (unsigned int i = 0; i < v.size() - 1; i++) {
unsigned int best = i;
for (unsigned int j = i + 1; j < v.size(); j++) {
if (v[j] < v[best]) {
best = j;
}
}
if (best != i) {
T temp = v[i];
v[i] = v[best];
v[best] = temp;
}
}
}

19

4.1.3 Algoritmos de Ordenacin Rpida:


Ordenacin Rpida (Quicksort)

Ordenacin rpida o "quicksort" es un algoritmo de ordenacin


rpida que usa un enfoque divide-y-vencers para la solucin de
problemas.
A diferencia de los algoritmos de ordenacin bsica que ya hemos
revisado, la ordenacin rpida usa recursin.
Dado un arreglo de elementos a ordenar, el algoritmo divide
recursivamente el arreglo en arreglos ms y ms pequeos.
Luego el algoritmo ordenacin rpida ordena estos arreglos
pequeos y combina los resultados para crear una versin
ordenada del arreglo original.
Debido a su naturaleza recursiva, la implantacin del algoritmo
ordenacin rpida puede ser difcil de entender.
20

Algoritmo ordenacin rpida


1.

2.

3.

4.

Si el tamao del arreglo es cero o uno, entonces regresa el arreglo. Este es


el caso base.
Selecciona un elemento del arreglo para ser usado como el elemento
pivote. Este es el paso de seleccin del pivote.
Crea dos nuevos arreglos. Coloca todos los elementos del arreglo original
que son menores que el elemento pivote en uno de estos subarreglos y
todos los elementos que son ms grandes que el elemento pivote en el
otro subarreglo. Este es el paso de la particin.
Regresa el arreglo que contiene el resultado del subarreglo ordenado
rpidamente que incluye los elementos menores que el pivote, seguidos
por el pivote, y luego por el resultado del subarreglo ordenado
rpidamente que incluye los elementos mayores que el pivote. Este es el
paso de divisin recursiva.
21

22

template <typename T>


void quick_sort(vector<T>& v, int low, int high) {
// Do not solve recursively when faced with only 1 or 2 elements
if (low == high) {return;}
else if (low + 1 == high) {
if (v[low] > v[high]) {
swap(v[low], v[high]);
}
return;
}
// select pivot
int middle = (low + high) / 2;T pivot = v[middle]; swap(v[middle], v[high]);
// partition
int i,j;
for (i = low, j = high - 1; ;) {
while (v[i] < pivot && i < j) i++;
while (pivot < v[j] && i < j) j--;
if (i < j) {swap(v[i], v[j]);} else {break;}
}
// place pivot in correct location
if (i != high - 1 && j != high - 1) {swap( v[i], v[high]);}
// quicksort sub-vectors
if (i == low && j == low) {quick_sort(v, low + 1, high);}
else if (i == high - 1 && j == high - 1) {quick_sort(v, low, high - 1);}
else {quick_sort(v, low, i - 1); quick_sort(v, i + 1, high);}
}

23

Vous aimerez peut-être aussi