Professional Documents
Culture Documents
Arrays
Mbuke, Juliana L.
Topics covered
• Creating an array data structure
• Searching an element
• Sorting algorithms
11/30/2016 3. Arrays 2
Introduction
• An array is a data structure that represents a collection of
data of the same type.
• It is the most basic sequence container used to store and
access a collection.
– Examples: A list of names
A list of temperatures
11/30/2016 3. Arrays 3
Advantages of arrays
• Simple to use
– Arrays are simple to understand and use.
11/30/2016 3. Arrays 4
Disadvantages of arrays
11/30/2016 3. Arrays 5
Creating an array data structure
11/30/2016 3. Arrays 6
Declaring arrays
11/30/2016 3. Arrays 7
One dimensional array
• This array is a list of variables that are all of the same type and are
referenced through a common name. An individual variable in an array is
called an array element.
• The elements of one dimensional array store all elements in a consecutive
order of entry into an array name
• The subscripts of an array are increased simultaneously one-by-one to
input values into an array
• From a previous mentioned syntax data_type arrayName[size];
– data_type is a valid C++ primitive data type, arrayName is the name of an array and size specifies
the number of elements in the array.
– For example;
» int num[5];
» Tell the compiler that:
• num is the name of the array, its type is integer int, it’s a one-dimensional
array, number of elements in an array is 5, each integer requires 2 bytes of
memory, and, array num allocates a contiguous memory block of 10 bytes.
11/30/2016 3. Arrays 8
Cont… declaring arrays
– The compiler allocates the space/memory for ten double elements for
array myList. When an array is created, its elements are assigned with
arbitrary values. To assign values to the elements use the following
syntax:
• arrayName[index] = value;
11/30/2016 3. Arrays 9
Cont… declaring arrays
The array myList has ten initilized elements of double type and int indexes from 0 to 9
11/30/2016 3. Arrays 10
Cont… declaring arrays
• C++ requires that the array size used to declare an array must be a constant expression. For
example, the following code is illegal:
int size = 4;
double myList[size]; // Wrong
• If arrays have the same element type, they can be declared together as follows;
– data_type arrayName[size1], arrayName[size2] , ………arrayName[sizeN];
11/30/2016 3. Arrays 11
Initializing an array
• C++ has a shorthand notation , known as the array initializer, which
combines declaring an array and initializing in one statement using the
following syntax;
– data_ type arrayName[size] = { value0, value1, value2………..valueN};
– For example;
• int stud_age[5] = { 14,15,12,13,16 };
• This statement declares and initializes the array stud_age with five elements. The
values stored in array stud_age are;
stud_age[0] = 14
stud_age[1] = 15
stud_age[2] = 12
stud_age[3] = 13
stud_age[4] = 16
• Using an array initializer you have to declare and initialize the array all in one
statement in either;
– int stud_age[5] = { 14,15,12,13,16}; or
– int stud_age[ ] = { 14,15,12,13,16}; // for this initialization C++ automatically figures out how
many element are in the array.
11/30/2016 3. Arrays 12
Processing arrays
• When processing array elements, you will often use a for loop.
– Reasons
• All of the elements in an array are of the same type, hence they are evenly
processed in the same manner by repeatedly using a loop
• Since the size of the array is known, it is natural to use a for loop
• The following program segment below shows the way data is entered into
one dimensional array
• The code will prompt user to input 5 integer values into the array num
int num[5];
for ( int i=0; i<5; i++)
cin>> num[i];
11/30/2016 3. Arrays 13
A program to enter any five integer values in an array num and
print their sum
11/30/2016 3. Arrays 14
Lab practice
11/30/2016 3. Arrays 15
Multi-dimensional arrays
• This is an array with more than one subscript
• Multi-dimensional array simulates a table of values or even multiple tables of values.
– Syntax for declaring multi-dimensional array is as discussed previously;
• data_type arrayName[size1][size2]…..[sizeN];
• The most commonly used table is a two-dimensional table (an array with two
subscript).
– Syntax for declaring a two-dimensional array is as follows;
• data_type arrayName[rowSize][columnSize];
Where data_type is a valid C++ primitive data type, arrayName is the name of an array and rowSize and columnSize
specifies the dimension of array.
For example;
» int matrix[10][12]; //declare the integer array table with 10 rows and 12 column
» The array tell the compiler that:
• matrix is the name of the array, its type is integer int, it’s a two-dimensional array,
number of elements in the array is 120 i.e. equal to the product of the two dimension
specifiers, since each integer value requires 2 bytes of memory therefore array matrix
allocates a contiguous memory block of 240 bytes.
11/30/2016 3. Arrays 16
Cont… declaring multi-dimensional arrays
• For example, if there are 3 students each having 5 different examination marks then matrix
array contains 3 rows and 5 columns in table form int matrix[3][5] will be;
Mark0 Mark1 Mark2 Mark3 Mark4
• Below shows memory representation in the matrix form of rows and columns;
Index[0][0] = 56
Index[0][1] = 43
Index[0][2] = 48
Index[0][3] = 65
………….........
………………....
Index[2][3] = 56
Index[2][4] = 31
11/30/2016 3. Arrays 17
Initializing a multi-dimensional array
• To make a multi-dimensional array initialization, match the array’s subscript.
• C++ allows initialization of a multi-dimensional array as if it were a single
dimensional array, BUT you have to make sure to keep track of the row order.
For instance;
int array1[2][4] = { 12 ,34, 54, 55,
32, 10, 43, 87 } ;
11/30/2016 3. Arrays 18
C++ program to demonstrate a multi-
dimensional array
11/30/2016 3. Arrays 19
Space and Time complexity
• Space complexity, regards how much memory is required to store a
program. It includes both fixed memory and variable memory.
• Time complexity, regards how much CPU time is required to execute the
program, the comparison statement is executing n times thus time
complexity is O(n) i.e Big O-notation
– Best case – is the one where the element is found in the first or second
location in the array then only one or two comparisons are required and an
algorithm terminates.
– Average case – occurs if the element is found somewhere in the middle of the
list, only n/2 times the comparison statement executes and algorithm
terminates.
– Worst case – when the element is in the last location or it may not be in the
list, then it executes the comparison statement n times.
11/30/2016 3. Arrays 20
Searching an element
11/30/2016 3. Arrays 21
Searching an element in array
11/30/2016 3. Arrays 22
Linear search algorithm
• This is a simple search algorithm for searching an element in
an array.
• It uses a loop to sequentially step through an array, starting
with the first element.
• It compares each element with the value being searched for
and stops when that value is found or the end of the array is
reached.
Note:
– Required to create an array with various elements and create a
linear search algorithm program.
– Find its complexity in terms of O notation
11/30/2016 3. Arrays 23
Efficiency of linear search
11/30/2016 3. Arrays 24
Binary search algorithm
• This is a search algorithm that finds the position of an
element (target value) within a sorted array.
• It requires the list to be in order (ascending or descending)
• Its said to be much more efficient than linear search algorithm
• The algorithm starts searching with the middle element;
– If the item is less than the middle element, it starts over searching the first half of the
list.
– If the item is greater than the middle element, the search starts over starting with the
middle element in the second half of the list.
– It then continues halving the list until the item is found.
Note:
– Required to create an array with various ordered elements and
create a binary search algorithm program.
– Find its complexity in terms of O notation
11/30/2016 3. Arrays 25
Sorting algorithms
11/30/2016 3. Arrays 26
Sorting elements in an array
11/30/2016 3. Arrays 27
The Bubble sort
11/30/2016 3. Arrays 28
Cont... Bubble sort
• Algorithm - words
– Compare each pair of adjacent elements from the
beginning of an array and, if they are in reversed
order, swap them.
– If at least one swap has been done, repeat step 1.
11/30/2016 3. Arrays 29
Bubble sort example
11/30/2016 3. Arrays 30
C++ code for bubble sort algorithm
void bubbleSort(int arr[], int n) {
bool swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < n - j; i++) {
if (arr[i] > arr[i + 1]) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
swapped = true;
}
}
}
}
11/30/2016 3. Arrays 31
Selection sort
11/30/2016 3. Arrays 32
Selection sort pseudo code
For Start is set to each subscript in Array from 0 through the next-to-last subscript
Set Index variable to Start
Set minIndex variable to Start
Set minValue variable to array[Start]
For Index is set to each subscript in Array from Start+1 through the next-to-last subscript
If array[Index] is less than minValue
Set minValue to array[Index]
Set minIndex to Index
End if
Increment Index
End For
Set array[minIndex] to array[Start]
Set array[Start] to minValue
End For
11/30/2016 3. Arrays 33
Selection sort example
11/30/2016 3. Arrays 34
C++ code for selection sort algorithm
void selectionSort(int arr[], int n) {
int i, j, minIndex, tmp;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
if (minIndex != i) {
tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
}
11/30/2016 3. Arrays 35
Lab practice
11/30/2016 3. Arrays 36