int

Programming in C++
1
Learning Outcome

At the end of this slide, student able to:


Understand how to use basic array and multidimensional array
Understand return values, parameters and arguments in
function.
2
What is array?
 The
array elements are accessed
through the index. Array indices are 0based; that is, they start from 0 to
arraySize-1.
3
Declaring, creating, initializing Using
the Shorthand Notation
double myList[4] = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the
following statements:
double myList[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
4
Initializing Character Arrays
char city[] = {'D', 'a', 'l', 'l', 'a', 's'};
char city[] = "Dallas";
This statement is equivalent to the preceding
statement, except that C++ adds the character '\0',
called the null terminator, to indicate the end of the
string, as shown in Figure 6.2. Recall that a character
that begins with the back slash symbol (\) is an
escape character.
'D'
city[0]
'a'
'l'
'l' 'a'
's'
'\0'
city[1] city[2] city[3] city[4] city[5] city[6]
5
Initializing arrays with random values
The following loop initializes the array myList with
random values between 0 and 99:
for (int i = 0; i < ARRAY_SIZE; i++)
{
myList[i] = rand() % 100;
}
6
animation
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the array is created
7
0
0
1
0
2
0
3
0
4
0
animation
Trace Program with Arrays
i becomes 1
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the array is created
8
0
0
1
0
2
0
3
0
4
0
animation
Trace Program with Arrays
i (=1) is less than 5
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the array is created
9
0
0
1
0
2
0
3
0
4
0
animation
Trace Program with Arrays
After this line is executed, value[1] is 1
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the first iteration
10
0
0
1
1
2
0
3
0
4
0
animation
Trace Program with Arrays
After i++, i becomes 2
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] +
values[i-1];
}
values[0] = values[1] +
values[4];
}
After the first iteration
0
0
1
1
2
0
3
0
4
0
11
animation
Trace Program with Arrays
i (= 2) is less than 5
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] +
values[i-1];
}
values[0] = values[1] +
values[4];
}
After the first iteration
0
0
1
1
2
0
3
0
4
0
12
animation
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the second iteration
13
0
0
1
1
2
3
3
0
4
0
animation
Trace Program with Arrays
After this, i becomes 3.
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the second iteration
14
0
0
1
1
2
3
3
0
4
0
animation
Trace Program with Arrays
i (=3) is still less than 5.
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the second iteration
15
0
0
1
1
2
3
3
0
4
0
animation
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the third iteration
16
0
0
1
1
2
3
3
6
4
0
animation
Trace Program with Arrays
After this, i becomes 4
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the third iteration
17
0
0
1
1
2
3
3
6
4
0
animation
Trace Program with Arrays
i (=4) is still less than 5
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the third iteration
18
0
0
1
1
2
3
3
6
4
0
animation
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the fourth iteration
19
0
0
1
1
2
3
3
6
4
10
animation
Trace Program with Arrays
After i++, i becomes 5
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = values[i] + values[i1];
}
values[0] = values[1] + values[4];
}
After the fourth iteration
0
0
1
1
2
3
3
6
4
10
20
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++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
After the fourth iteration
0
0
1
1
2
3
3
6
4
10
21
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++)
{
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
22
0
11
1
1
2
3
3
6
4
10
Printing arrays
To print an array, you have to print each element in
the array using a loop like the following:
for (int i = 0; i < ARRAY_SIZE; i++)
{
cout << myList[i] << " ";
}
23
Printing Character Array
For a character array, it can be printed using one print
statement. For example, the following code displays
Dallas:
char city[] = "Dallas";
cout << city;
24
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];
}
25
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];
}
26
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];
}
27
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;
}
}
28
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;
}
29
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;
30
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
31
Run
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
32
Run
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
33
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.
34
Pass-by-Reference
Passing an array variable means that the starting
address of the array is passed to the formal
parameter. The parameter inside the function
references to the same array that is passed to the
function. No new arrays are created. This is passby-reference.
PassByReferenceDemo
Run
35
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
36
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++.
37
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
38
Run
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
newList
1
2
3
4
5
6
0
0
0
0
0
0
39
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
newList
1
2
3
4
5
6
0
0
0
0
0
0
40
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
newList
1
2
3
4
5
6
0
0
0
0
0
0
41
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
newList
1
2
3
4
5
6
0
0
0
0
0
1
42
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
newList
1
2
3
4
5
6
0
0
0
0
0
1
43
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
newList
1
2
3
4
5
6
0
0
0
0
0
1
44
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];
}
}
list
newList
1
2
3
4
5
6
0
0
0
0
2
1
45
i = 1 and j = 4
Assign list[1] to result[4]
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
newList
1
2
3
4
5
6
0
0
0
0
2
1
46
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 (=2) is still less than 6
newList[j] = list[i];
}
}
list
newList
1
2
3
4
5
6
0
0
0
0
2
1
47
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
newList
1
2
3
4
5
6
0
0
0
3
2
1
48
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
newList
1
2
3
4
5
6
0
0
0
3
2
1
49
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
newList
1
2
3
4
5
6
0
0
0
3
2
1
50
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
newList
1
2
3
4
5
6
0
0
4
3
2
1
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];
}
After this, i becomes 4 and
j becomes 1
}
list
1
2
3
4
5
6
newList
0
0
4
3
2
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];
}
i (=4) is still less than 6
}
list
1
2
3
4
5
6
newList
0
0
4
3
2
1
53
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
newList
1
2
3
4
5
6
0
5
4
3
2
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];
}
After this, i becomes 5 and
j becomes 0
}
list
newList
1
2
3
4
5
6
0
5
4
3
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];
}
i (=5) is still less than 6
}
list
newList
1
2
3
4
5
6
0
5
4
3
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 = 5 and j = 0
}
Assign list[i] to result[j]
}
list
newList
1
2
3
4
5
6
6
5
4
3
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];
After this, i becomes 6 and
}
j becomes -1
}
list
newList
1
2
3
4
5
6
6
5
4
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];
i (=6) < 6 is false. So exit
the loop.
}
}
list
1
2
3
4
5
6
newList
6
5
4
3
2
1
59
Problem: Counting Occurrence of Each
Letter


Generate 100 lowercase
letters randomly and
assign to an array of
characters.
Count the occurrence of
each letter in the array.
CountLettersInArray
chars[0]
counts[0]
chars[1]
counts[1]
…
…
…
…
…
…
…
…
chars[98]
counts[24]
chars[99]
counts[25]
Run
60
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.
int linearSearch(const int list[], int key, int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
if (key == list[i])
return i;
[0] [1] [2] …
}
list
return -1;
key Compare key with list[i] for i = 0, 1, …
}
61
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.
62
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
63
From Idea to Solution
int linearSearch(const int list[], int key, int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
if (key == list[i])
return i;
[0] [1] [2] …
}
list
return -1;
key Compare key with list[i] for i = 0, 1, …
}
Trace the function
int[]
int i
int j
int k
list = {1, 4, 4, 2, 5, -3, 6, 2};
= linearSearch(list, 4); // returns 1
= linearSearch(list, -4); // returns -1
= linearSearch(list, -3); // returns 5
64
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.
65
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.

66
animation
Binary Search
Key
List
8
1
2
3
4
6
7
8
9
8
1
2
3
4
6
7
8
9
8
1
2
3
4
6
7
8
9
67
Binary Search, cont.
key is 11
low
key < 50
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list
2
low
key > 7
mid
4
7 10 11 45
mid
[0] [1] [2] [3] [4] [5]
list 2 4 7 10 11 45
mid
high
[3] [4] [5]
key == 11
50 59 60 66 69 70 79
high
low
list
10 11 45
68
high
low
Binary Search,
cont.
key is 54
mid
high
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
key > 50
list
2
4
7 10 11 45
50 59 60 66 69 70 79
low
key < 66
mid
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list
59 60 66 69 70 79
low mid
high
[7] [8]
key < 59
high
list
59 60
low
high
[6] [7] [8]
59 60
69
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.
70
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;
}
71
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.
72
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
with 2 (the first) in the list
2
9
5
4
8
1
6
8
2
6
The number 1 is now in the
correct position and thus no
longer needs to be considered.
swap
Select 2 (the smallest) and swap it
with 9 (the first) in the remaining
list
1
Select 4 (the smallest) and swap it
with 5 (the first) in the remaining
list
1
2
5
4
8
9
6
The number 2 is now in the
correct position and thus no
longer needs to be considered.
5 is the smallest and in the right
position. No swap is necessary
1
2
4
5
8
9
6
The number 6 is now in the
correct position and thus no
longer needs to be considered.
Select 6 (the smallest) and swap it
with 8 (the first) in the remaining
list
1
6
The number 5 is now in the
correct position and thus no
longer needs to be considered.
Select 8 (the smallest) and swap it
with 9 (the first) in the remaining
list
1
2
4
5
6
9
8
The number 6 is now in the
correct position and thus no
longer needs to be considered.
Since there is only one element
remaining in the list, sort is
completed
1
2
4
5
6
8
9
The number 8 is now in the
correct position and thus no
longer needs to be considered.
9
5
4
swap
swap
2
4
5
8
9
swap
73
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] ...
74
list[10]
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;
}
}
75
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;
}
}
76
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;
}
77
Insertion Sort
Optional
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted
The insertion sort
algorithm sorts a list
of values by
repeatedly inserting
an unsorted element
into a sorted sublist
until the whole list
is sorted.
Step 1: Initially, the sorted sublist contains the
first element in the list. Insert 9 to the sublist.
2
9
5
4
8
1
6
Step2: The sorted sublist is {2, 9}. Insert 5 to the
sublist.
2
9
5
4
8
1
6
Step 3: The sorted sublist is {2, 5, 9}. Insert 4 to
the sublist.
2
5
9
4
8
1
6
Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8
to the sublist.
2
4
5
9
8
1
6
Step 5: The sorted sublist is {2, 4, 5, 8, 9}. Insert
1 to the sublist.
2
4
5
8
9
1
6
Step 6: The sorted sublist is {1, 2, 4, 5, 8, 9}.
Insert 6 to the sublist.
1
2
4
5
8
9
6
Step 7: The entire list is now sorted
1
2
4
5
6
8
9
78
animation
Insertion Sort
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted
2
2
2
1
9
5
4
2
5
9
5
4
4
4
8
5
8
8
9
6
1
1
1
8
6
2
9
5
4
8
1
6
2
4
5
9
8
1
6
1
2
4
5
8
9
6
6
6
9
79
How to Insert?
Optional
The insertion sort
algorithm sorts a list
of values by
repeatedly inserting
an unsorted element
into a sorted sublist
until the whole list
is sorted.
[0] [1] [2] [3] [4] [5] [6]
list
2
5 9
4
Step 1: Save 4 to a temporary variable currentElement
[0] [1] [2] [3] [4] [5] [6]
list
2
5
9
Step 2: Move list[2] to list[3]
[0] [1] [2] [3] [4] [5] [6]
list
2
5 9
Step 3: Move list[1] to list[2]
[0] [1] [2] [3] [4] [5] [6]
list
2
4
5 9
Step 4: Assign currentElement to list[1]
80