You are on page 1of 36

3.

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

• Why do we need arrays?


– Imagine keeping track of 5 test scores, or 100, or 1000 in memory
• How would you name all the variables?
• How would you process each of the variables?

11/30/2016 3. Arrays 3
Advantages of arrays

• Data accessing can be random and is faster


– Using arrays, we can access any data item efficiently just by
specifying the index of that item, For example, we can access ith
item in the array A by specifying A (i). The time taken to access
the data in a (0) and time taken to access the data in a (10000) is
same

• Simple to use
– Arrays are simple to understand and use.

11/30/2016 3. Arrays 4
Disadvantages of arrays

• The size of the array is fixed


– In static allocation technique, a fixed amount of memory is allocated before
the start of execution for static arrays and during execution for dynamic arrays.
The memory required for most of the applications often cannot be predicted
while writing a program. If more memory is allocated and the application
requires less memory, it results in wastage of memory space. If less memory
space is allocated and if the applications require more memory space during
execution, it is not possible to allocate extra memory for arrays during
execution.
• Array items are stored contiguously
– Some time enough contiguous memory locations may not be available. There
are situations where a number of chunks of contiguous memory locations are
available. Even though the total free memory space is sufficient, this space
cannot be used since arrays require contiguous storage space.

11/30/2016 3. Arrays 5
Creating an array data structure

11/30/2016 3. Arrays 6
Declaring arrays

• Arrays are of two types namely single dimensional


arrays and multi-dimensional arrays
• To declare an array you need to specify its element type
and size using the following syntax;
– For single/one dimensional array
• data_type arrayName[size]

– For multi-dimensional array


• data_type arrayName[size][size] , for two dimensional array
• data_type arrayName[size1][size2]…..[sizeN] , multiple dimensional array

Note: [size] is an actual arraySize

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 arraySize that is [size] must be an integer greater than


zero. For example, the following statement declares an array
of ten double values:
– double myList[10]

– 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

But it would be OK, if size is a constant as follow:


const int size = 4;
double myList[size]; // Correct

• If arrays have the same element type, they can be declared together as follows;
– data_type arrayName[size1], arrayName[size2] , ………arrayName[sizeN];

– The variables are separated by commas, for example;


• double list1[10], list2[25];

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

• Using the example conducted on class, rewrite that program


using Class Students;
– Create data members name and marks
– In the main function create a class object of a student
– Declare an array
– The program shall capture class object (ex. S[i]) name and marks and later
displays/prints those information on the screen

• Conduct a review on the following;


• Passing arrays to functions
• Return arrays from functions

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

Row 0 for 1st student 56 43 48 65 54


Row 1 for 2nd student 65 54 76 34 54
Row 2 for 3rd student 48 67 54 56 31

• 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 } ;

• Otherwise, a multi-dimensional array array1 above may be declared, created


and initialized with nested braces as follows;
int array1[2][4] = { { 12 ,34, 54, 55 } ,
{ 32, 10, 43, 87 }
};
Which is equivalent to
int array1[2][4];
array1[0][0] = 12; array1[0][1] = 34; array1[0][2] = 54; array1[0][3] = 55;
array1[1][0] = 32; array1[1][1] = 10; array1[1][2] = 43; array1[1][3] = 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

• This is a process of looking for a specific element in an


array.
• For instance; looking whether a certain score is included in a list of scores.
• There are many algorithms and data structures which are
devoted to searching.
• In array data structure two common approaches are
normally applied when searching for an item namely;
– Linear search
– Binary search

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

• The advantage is its simplicity.


– It is easy to understand
– Easy to implement
– It can be applied to both sorted and unsorted array

• The disadvantage is its inefficiency


– If there are 20,000 items in the array and what you are
looking for is in the 19,999th element, you need to search
through the entire list.

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

• Sorting algorithms are used to arrange random data


into some order.

• We will be discussing two types of sorting algorithms


namely;
– Bubble Sort
– Selection Sort

11/30/2016 3. Arrays 27
The Bubble sort

• An easy way to arrange data in ascending or descending


order.
• Pseudo code:
Do
Set count variable to 0
For count is set to each subscript in Array from 0 to the next-to-last subscript
If array[count] is greater than array[count+1]
swap them
set swap flag to true
end if
End for
While any elements have been swapped.

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

• Compared to the bubble sort that moves only one


element at a time,
• The selection sort moves elements immediately to their
final position in the array so it makes fewer exchanges.

• Selection sort is notable for its programming simplicity


and it can over perform other sorts in certain situations

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

• Re-write both bubble sort algorithm and selection sort


algorithm programs
– In flow charts
– In a manner you can understand.

• Run the programs

11/30/2016 3. Arrays 36

You might also like