Está en la página 1de 89

Ch.

7 Arreglos Unidimensionales

1
Motivaciones
Frecuentemente se necesita almacenar un numero grande
valores durante la ejecución de un programa. Supongamos que
nccesita leer un cineto de numeros., calcular su promedio, y
cuantos están sobre el prmedio. Su programa primero lee los
numeros y calcula el promedio y compara cada numero con el
promedio para determinar cuales están sobre el promedio. Los
numeros deben ser almacenados en variables en el orden que
requiere la tarea. Usted tiene que declarar un ciento de
variables y escribiur repetidamente identicamnete el ciento de
numeros. En este punto es practicamente imposible escribir un
programa en ese sentido. Entonces como se resuelve el
probelma?

2
Objectivos
 Describir porque es necesario los arreglos (array) en la programacion. (§7.1).
 Declaracion de arreglos (§7.2.1).
 Accesando a los elementos usando variables indexadas. (§7.2.2).
 Inicializar valores en un arreglo. (§7.2.3).
 Programar operaciones comunes con un arreglo (displaying arrays, summing all
elements, finding min and max elements, random shuffling, shifting elements)
(§7.2.4).
 Arreglos en problemas de LottoNumbers y DeckOfCards (§§7.3-7.4).
 Desarrollar e invocar funciones con argumentos de arreglos. (§§7.5-7.6).
 To develop functions involving array parameters in the CountLettersInArray
problem (§7.7).
 Buscar elementos usando metodo linear (§7.8.1) o algoritmo de busqueda
binaria(§7.8.2).
 Ordenando un arreglo usando el metodo de selection. (§7.9.1)
 Ordenando un arreglo usando el metodo de insercion. (§7.9.2).
 Procesando cadena de caracteres strings C-strings (§7.10).
3
Introduccion a los Arrays
Arreglo es una estructura de datos que representa una
colección del mismo tipo de datos.
doublemyList [10];

myList[0] 5.6
myList[1] 4.5
myList[2] 3.3
myList[3] 13.2
myList[4] 4.0
Arrayelement at
myList[5] 34.33 Element value
index5
myList[6] 34.0

myList[7] 45.45

myList[8] 99.993

myList[9] 111.23

4
Declararación de variables tipo Array
datatype arrayRefVar[arraySize];
Ejemplo:
double myList[10];

C++ requiere que el tamaño usado para declarar un arreglo debe ser
una constante. Por ejemplo, el siguiente codigo es ilegal:
int size = 4;
double myList[size]; // Incorrecto
Pero es OK, si el tamaño es una constante como la siguiente:
const int size = 4;
double myList[size]; // Correcto

5
Inicializacion de Valores Arbitrarios
Cuando un arreglo es creado, sus elementos son
asignados con valores arbitrarios.

6
Indexacion de Variables
Los elementos de un arreglo son accesados mediante el
indice. Los indices del arreglo son basados en 0, esto es
que comienzan de cero hasta el tamaño -1. En el ejemplo
de la Figure 6.1, myList mantiene diez valores double y sus
valores de los indices son de 0 a 9.

Cada elemento en el array es representedo usando la


siguiente syntaxis, conocido como un indexed variable:

arrayName[index];

Por ejemplo, myList[9] representa el ultimo elemento en el


arreglo myList.
7
Usando Variables Indexadas
Despues de creado un arreglo(array), una
variable indexada puede ser usada en el mismo
sentido como una variable regular. Por ejemplo,
en el codigo siguiente suma el valor de
myList[0] y myList[1] y asigna en myList[2].

myList[2] = myList[0] + myList[1];

8
No Chequeo de Limites
C++ no chequea los limites de un arreglo. Así, el
acceso a los elementos del arreglo utilizando
subíndices más allá del límite (por ejemplo, myList
[-1] y myList [11]) no provoca errores de sintaxis,
pero el sistema operativo puede reportar una
violación de acceso a memoria.

9
Initializando Arreglos
Declacion, creacion, initializacion en un paso:
dataType arrayName[arraySize] = {value0, value1,
..., valuek};

double myList[4] = {1.9, 2.9, 3.4, 3.5};

10
Declarion, creacion, inicializacion
Usando la Notacion Corta
double myList[4] = {1.9, 2.9, 3.4, 3.5};

Esta notación corta es equivalente a las


sentencias siguientes:
double myList[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

11
Precaucion
Utilizando la notación abreviada, tiene
que declarar, crear y inicializar la matriz
todo en una sentencia. La división podría
causar un error de sintaxis. Por ejemplo,
lo siguiente es incorrecto:

double myList[4];
myList = {1.9, 2.9, 3.4, 3.5};

12
Tamaño Implicito
C++ le permite a usted omitir el tamaño del arreglo
cuando declara y crea utilizando la inicializacion.
Por ejemplo, la siguiente declaracion es valida:

double myList[] = {1.9, 2.9, 3.4, 3.5};

C++ automaticamente calcula cuantos elementos


hay en un arreglo.

13
Initializacion Parcial
C++ le permite initializar parte del arreglo. Por
ejemplo, la siguiente sentencia asigna los valores
1.9, 2.9 al primer y segundo elemento del arreglo.
Los otros dos elementos son incializados con ceros.
Note que el arreglo es declaraado, pero no
inicializa, todos los elementos pueden contener
“garbage”, como todas las variables locales.

double myList[4] = {1.9, 2.9};

14
Initializacion de Arreglo de Caracteres
char city[] = {'D', 'a', 'l', 'l', 'a', 's'};

char city[] = "Dallas";


Esta sentencia es equivalente al precedente, excepto que
C++ añade el caracter '\0', llamado null terminator, para
indicar el fin del string, como se muestra en Figura 6.2.
Recordemos que un caracter que comienza con el símbolo
de barra invertida (\) es un carácter de escape

'D' 'a' 'l' 'l' 'a' 's' '\0'


city[0] city[1] city[2] city[3] city[4] city[5] city[6]

15
Initializando arreglos con valores random

La siguiente repeticion inicializa el arreglo myList con


valores aleatorios(random) entre 0 y 99:

for (int i = 0; i < ARRAY_SIZE; i++)


{
myList[i] = rand() % 100;
}

16
animation
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values

int main()
{ After the array is created

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 0
{ 2 0

values[i] = values[i] + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

17
animation
Trace Program with Arrays
i becomes 1

int main()
{
After the array is created
int values[5];
for (int i = 1; i < 5; i++) 0 0

{ 1 0

2 0
values[i] = values[i] + values[i-1];
3 0
} 4 0
values[0] = values[1] + values[4];
}

18
animation
Trace Program with Arrays
i (=1) is less than 5

int main()
{
After the array is created
int values[5];
for (int i = 1; i < 5; i++) 0 0
{ 1 0

values[i] = values[i] + values[i-1]; 2 0

} 3 0

4 0
values[0] = values[1] + values[4];
}

19
animation
Trace Program with Arrays
After this line is executed, value[1] is 1

int main()
{ After the first iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1

{ 2 0

values[i] = values[i] + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

20
animation

Trace Program with Arrays


After i++, i becomes 2

int main()
{
int values[5]; After the first iteration

for (int i = 1; i < 5; i++) 0 0

{ 1

2
1

0
values[i] = values[i] + 3 0

values[i-1]; 4 0

}
values[0] = values[1] +
values[4];
}

21
animation
Trace Program with Arrays
i (= 2) is less than 5
int main()
{
int values[5];
for (int i = 1; i < 5; i++) After the first iteration

{ 0 0

values[i] = values[i] + 1 1

values[i-1]; 2 0

3 0
} 4 0
values[0] = values[1] +
values[4];
}

22
animation
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1

{ 2 3

values[i] = values[i] + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

23
animation
Trace Program with Arrays
After this, i becomes 3.

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1

{ 2 3

values[i] = values[i] + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

24
animation
Trace Program with Arrays
i (=3) is still less than 5.

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1

{ 2 3

values[i] = values[i] + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

25
animation
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1

{ 2 3

values[i] = values[i] + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}

26
animation
Trace Program with Arrays
After this, i becomes 4

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1

{ 2 3

values[i] = values[i] + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}

27
animation
Trace Program with Arrays
i (=4) is still less than 5

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1

{ 2 3

values[i] = values[i] + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}

28
animation
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)

int main()
{ After the fourth iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1

{ 2 3

values[i] = values[i] + values[i-1]; 3 6

} 4 10

values[0] = values[1] + values[4];


}

29
animation
Trace Program with Arrays
After i++, i becomes 5

int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{ After the fourth iteration
values[i] = values[i] + values[i-1];
} 0 0
values[0] = values[1] + values[4]; 1 1

} 2 3

3 6

4 10

30
animation

Trace Program with Arrays


i ( =5) < 5 is false. Exit the loop

int main()
{
int values[5];
for (int i = 1; i < 5; i++) After the fourth iteration

{
0 0
values[i] = values[i] + values[i-1]; 1 1

} 2 3

values[0] = values[1] + values[4]; 3 6

4 10
}

31
animation
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)

int main()
{
int values[5];
for (int i = 1; i < 5; i++) 0 11

{ 1 1

values[i] = values[i] + values[i-1]; 2 3

} 3 6

values[0] = values[1] + values[4]; 4 10

32
que comienza con el símbolo de
barra invertida (\) es un carácter
deunescape
Para imprimir (mostrar) arreglo, tiene que imprimir cada
elemento del arreglo usando una repeticion(loop) como el
siguiente:

for (int i = 0; i < ARRAY_SIZE; i++)


{
cout << myList[i] << " ";
}

33
For a character array, it can be printed using one print
statement. For example, the following code displays
Dallas:

char city[] = "Dallas";


cout << city;

34
Copying Arrays
Can you copy array using a syntax like this?
list = myList;

This is not allowed in C++. You have to copy individual


elements from one array to the other as follows:

for (int i = 0; i < ARRAY_SIZE; i++)


{
list[i] = myList[i];
}
35
Summing All Elements
Use a variable named total to store the sum. Initially total
is 0. Add each element in the array to total using a loop
like this:

double total = 0;
for (int i = 0; i < ARRAY_SIZE; i++)
{
total += myList[i];
}

36
Finding the Largest Element
Use a variable named max to store the largest element.
Initially max is myList[0]. To find the largest element in
the array myList, compare each element in myList with
max, update max if the element is greater than max.

double max = myList[0];


for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max) max = myList[i];
}

37
Finding the smallest index of the
largest element
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max)
{
max = myList[i];
indexOfMax = i;
}
}
38
Random Shuffling

srand(time(0));
for (int i = 0; i < ARRAY_SIZE; i++)
{
// Generate an index randomly
int index = rand() % ARRAY_SIZE;
double temp = myList[i];
myList[i] = myList[index];
myList[index] = temp;
}

39
Shifting Elements

double temp = myList[0]; // Retain the first element


// Shift elements left
for (int i = 1; i < myList.length; i++)
{
myList[i - 1] = myList[i];
}
// Move the first element to fill in the last position
myList[myList.length - 1] = temp;

40
Problem: Lotto Numbers
Your grandma likes to play the Pick-10 lotto. Each
ticket has 10 unique numbers ranging from 1 to 99.
Every time she buys a lot of tickets. She likes to
have her tickets to cover all numbers from 1 to 99.
Write a program that reads the ticket numbers from
a file and checks whether all numbers are covered.
Assume the last number in the file is 0.

LottoNumbers Run

41
Problem: Deck of Cards
The problem is to write a program that picks four cards randomly
from a deck of 52 cards. All the cards can be represented using an
array named deck, filled with initial values 0 to 52, as follows:

int deck[52];
// Initialize cards
for (int i = 0; i < NUMBER_OF_CARDS; i++)
deck[i] = i;

deck[0] to deck[12] are Clubs, deck[13] to deck[25] are Diamonds,


deck[26] to deck[38] are Hearts, and deck[39] to deck[51] are
Spades. Listing 6.2 gives the solution to the problem.
DeckOfCards Run
42
Passing Arrays to Functions
Just as you can pass single values to a function,
you can also pass an entire array to a function.
Listing 6.3 gives an example to demonstrate how
to declare and invoke this type of functions.

PassArrayDemo

Run

43
Passing Size along with Array
Normally when you pass an array to a function, you
should also pass its size in another argument. So the
function knows how many elements are in the array.
Otherwise, you will have to hard code this into the
function or declare it in a global variable. Neither is
flexible or robust.

44
const Parameters
Passing arrays by reference makes sense for performance
reasons. If an array is passed by value, all its elements must
be copied into a new array. For large arrays, it could take
some time and additional memory space. However, passing
arrays by reference could lead to errors if your function
changes the array accidentally. To prevent it from
happening, you can put the const keyword before the array
parameter to tell the compiler that the array cannot be
changed. The compiler will report errors if the code in the
function attempts to modify the array.

ConstArrayDemo Compile error


46
Returning an Array from a Function
Can you return an array from a function using a similar
syntax? For example, you may attempt to declare a function
that returns a new array that is a reversal of an array as
follows:

// Return the reversal of list


int[] reverse(const int list[], int size)
This is not allowed in C++.

47
Modifying Arrays in Functions, cont.
However, you can circumvent this restriction by passing
two array arguments in the function, as follows:
// newList is the reversal of list
void reverse(const int list[], list newList[], int size)

list

newList

ReverseArray Run

48
animation

Trace the reverse Function


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 0

49
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);
i = 0 and j = 5

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 0

50
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2); i (= 0) is less than 6

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 0

51
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i = 0 and j = 5
} Assign list[0] to result[5]
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 1

52
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; After this, i becomes 1 and j
} becomes 4
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 1

53
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

i (=1) is less than 6


void reverse(const int list[], int newList[], int size)
{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 1

54
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 1 and j = 4
Assign list[1] to result[4]
}
list 1 2 3 4 5 6

newList 0 0 0 0 2 1

55
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} After this, i becomes 2 and j
becomes 3
}

list 1 2 3 4 5 6

newList 0 0 0 0 2 1

56
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i (=2) is still less than 6
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 2 1

57
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 2 and j = 3
Assign list[i] to result[j]
}

list 1 2 3 4 5 6

newList 0 0 0 3 2 1

58
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; After this, i becomes 3 and j
} becomes 2

list 1 2 3 4 5 6

newList 0 0 0 3 2 1

59
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i (=3) is still less than 6
}

list 1 2 3 4 5 6

newList 0 0 0 3 2 1

60
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 3 and j = 2
Assign list[i] to result[j]
}

list 1 2 3 4 5 6

newList 0 0 4 3 2 1

61
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} After this, i becomes 4 and j
} becomes 1

list 1 2 3 4 5 6

newList 0 0 4 3 2 1

62
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i (=4) is still less than 6
}

list 1 2 3 4 5 6

newList 0 0 4 3 2 1

63
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
i = 4 and j = 1
newList[j] = list[i]; Assign list[i] to result[j]
}
}

list 1 2 3 4 5 6

newList 0 5 4 3 2 1

64
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} After this, i becomes 5 and j
becomes 0
}

list 1 2 3 4 5 6

newList 0 5 4 3 2 1

65
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i (=5) is still less than 6
}

list 1 2 3 4 5 6

newList 0 5 4 3 2 1

66
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 5 and j = 0
Assign list[i] to result[j]
}

list 1 2 3 4 5 6

newList 6 5 4 3 2 1

67
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
After this, i becomes 6 and j
} becomes -1
}

list 1 2 3 4 5 6

newList 6 5 4 3 2 1

68
animation

Trace the reverse Method, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i (=6) < 6 is false. So exit
} the loop.

list 1 2 3 4 5 6

newList 6 5 4 3 2 1

69
Problem: Counting Occurrence of Each
Letter

 Generate 100 lowercase


chars[0] counts[0]
letters randomly and assign chars[1] counts[1]

to an array of characters. … … … …
… … … …
 Count the occurrence of each chars[98] counts[24]
letter in the array. chars[99] counts[25]

CountLettersInArray Run
70
Searching Arrays
Searching is the process of looking for a specific element in
an array; for example, discovering whether a certain score is
included in a list of scores. Searching is a common task in
computer programming. There are many algorithms and
data structures devoted to searching. In this section, two
commonly used approaches are discussed, linear search and
binary search.
i
ntlin
earSea
rch
(co
nstintlis
t[]
,intk
ey,i ntarray
S i
ze)
{
fo
r(inti=0 ;i<a rray
Siz
e;i++
)
{
if(key==list
[i])
r
eturni; [
0][
1][
2]…
} lis
t
re
tur
n-1
; k
eyC
omp
ar
e k
eywithlis
t[
i]f
ori=0
,1,…
}

71
Linear Search
The linear search approach compares the key
element, key, sequentially with each element in
the array list. The method continues to do so
until the key matches an element in the list or
the list is exhausted without a match being
found. If a match is made, the linear search
returns the index of the element in the array
that matches the key. If no match is found, the
search returns -1.

72
animation

Linear Search Animation


Key List
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8
73
From Idea to Solution
i
ntlin
earSea
rch
(co
nstintlis
t[]
,intk
ey,i ntarray
S i
ze)
{
fo
r(inti=0 ;i<a rray
Siz
e;i++
)
{
if(key==list
[i])
r
eturni; [
0][
1][
2]…
} lis
t
re
tur
n-1
; k
eyC
omp
ar
e k
eywithlis
t[
i]f
ori=0
,1,…
}

Trace the function


int[] list = {1, 4, 4, 2, 5, -3, 6, 2};
int i = linearSearch(list, 4); // returns 1
int j = linearSearch(list, -4); // returns -1
int k = linearSearch(list, -3); // returns 5

74
Binary Search
For binary search to work, the elements in the
array must already be ordered. Without loss of
generality, assume that the array is in
ascending order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key with
the element in the middle of the array.

75
Binary Search, cont.
Consider the following three cases:
 If the key is less than the middle element,
you only need to search the key in the first
half of the array.
 If the key is equal to the middle element,
the search ends with a match.
 If the key is greater than the middle
element, you only need to search the key in
the second half of the array.
76
animation

Binary Search

Key List

8 2 3 4 6 7 8
8 1 2 3 4 7 8
8 1 2 3 4 6 7 8

77
Binary Search, cont.
k
eyis1
1 lo
w m
id h
igh

k
ey<5
0 [0
] [1
] [2
] [3
] [4
] [5
] [6
] [7
] [8
] [9
][1
0][1
1][1
2]
list 2 4 7 1
0114
5 5
0596
0666
9707
9
lo
w m
id h
igh

[0
] [1
] [2
] [3
] [4
] [5
]
k
ey>7 list 2 4 7 1 01 14 5

w m
lo id h
igh

[3
] [4
] [5
]
ey=
k =11 list 1
0114
5

78
key is 54 Binary
low Search,midcont. high

key >50 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list 2 4 7 10 11 45 50 59 60 66 69 70 79
low mid high

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
key <66 list 59 60 66 69 70 79

lowmid high

[7] [8]
key < 59 list 59 60

low high

[6] [7] [8]


59 60
79
Binary Search, cont.
The binarySearch method returns the index of the
search key if it is contained in the list. Otherwise,
it returns –insertion point - 1. The insertion point is
the point at which the key would be inserted into
the list.

80
From Idea to Solution
int binarySearch(const int list[], int key, int arraySize)
{
int low = 0;
int high = arraySize - 1;

while (high >= low)


{
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}

return –low - 1;
}

81
Sorting Arrays
Sorting, like searching, is also a common task in
computer programming. It would be used, for
instance, if you wanted to display the grades from
Listing 6.2, AssignGrade.cpp, in alphabetical order.
Many different algorithms have been developed for
sorting. This section introduces two simple, intuitive
sorting algorithms: selection sort and insertion sort.

82
Selection Sort
Selection sort finds the largest number in the list and places it last. It then finds the largest
number remaining and places it next to last, and so on until the list contains only a single
number. Figure 6.17 shows how to sort the list {2, 9, 5, 4, 8, 1, 6} using selection sort.
swap

Select 1 (the smallest) and swap it 2 9 5 4 8 1 6


with 2 (the first) in the list
swap
The number 1 is nowin the
Select 2 (the smallest) and swap it 1 9 5 4 8 2 6 correct position and thus no
with 9 (the first) in the remaining longer needs to be considered.
list swap

The number 2 is nowin the


Select 4 (the smallest) and swap it 1 2 5 4 8 9 6 correct position and thus no
with 5 (the first) in the remaining longer needs to be considered.
list
The number 6 is nowin the
5 is the smallest and in the right 1 2 4 5 8 9 6 correct position and thus no
position. No swap is necessary longer needs to be considered.
swap

The number 5 is nowin the


Select 6 (the smallest) and swap it 1 2 4 5 8 9 6 correct position and thus no
with 8 (the first) in the remaining longer needs to be considered.
list swap

The number 6 is nowin the


Select 8 (the smallest) and swap it 1 2 4 5 6 9 8 correct position and thus no
with 9 (the first) in the remaining longer needs to be considered.
list

The number 8 is nowin the


Since there is only one element 1 2 4 5 6 8 9 correct position and thus no
remaining in the list, sort is longer needs to be considered.
completed

83
From Idea to Solution
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

...

list[0] list[1] list[2] list[3] ... list[10]

84
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i; j < listSize; j++)
{
if (currentMin > list[j])
{
currentMin = list[j];
currentMinIndex = j;
}
}

85
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i; j < listSize; j++)
{
if (currentMin > list[j])
{
currentMin = list[j];
currentMinIndex = j;
}
}

86
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
if (currentMinIndex != i)
{
list[currentMinIndex] = list[i];
list[i] = currentMin;
}

87
Optional
Insertion Sort
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted
The insertion sort Step 1: Initially, the sorted sublist contains the 2 9 5 4 8 1 6
algorithm sorts a list first element in the list. Insert 9 to the sublist.

of values by
Step2: The sorted sublist is {2, 9}. Insert 5 to the 2 9 5 4 8 1 6
repeatedly inserting sublist.
an unsorted element
into a sorted sublist Step 3: The sorted sublist is {2, 5, 9}. Insert 4 to 2 5 9 4 8 1 6
the sublist.
until the whole list
is sorted. Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8 2 4 5 9 8 1 6
to the sublist.

Step 5: The sorted sublist is {2, 4, 5, 8, 9}. Insert 2 4 5 8 9 1 6


1 to the sublist.

Step 6: The sorted sublist is {1, 2, 4, 5, 8, 9}. 1 2 4 5 8 9 6


Insert 6 to the sublist.

Step 7: The entire list is nowsorted 1 2 4 5 6 8 9

88
animation

Insertion Sort
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted

2 9 5 4 8 1 6
2 9 5 4 8 1 6
2 5 9 4 8 1 6
2 4 5 9 8 1 6
2 4 5 8 9 1 6
1 2 4 5 8 9 6
1 2 4 5 6 8 9

89
Optional
How to Insert?

The insertion sort [0


] [1
] [2
] [3
] [4
] [5
] [6
]
algorithm sorts a list t 2 59 4
lis S
te
p1:S
ave4toate
m p
ora
ryv
aria
blec
urre
ntE
le
m e
nt

of values by [0
] [1
] [2
] [3
] [4
] [5
] [6
]
repeatedly inserting lis
t 2 5 9 S
te
p2:M
ov
elis
t[2
]tolis
t[3
]
an unsorted element [0
] [1
] [2
] [3
] [4
] [5
] [6
]
into a sorted sublist lis
t 2 59 S
te
p3:M
ov
elis
t[1
]tolis
t[2
]
until the whole list
[0
] [1
] [2
] [3
] [4
] [5
] [6
]
is sorted. lis
t 2 4 59 S
te
p4:A
ss
ignc
urre
ntE
le
m e
nttolis
t[1
]

90