0% found this document useful (0 votes)
57 views22 pages

Data Structures & Algorithms: by L. Mutanu

The document discusses arrays and various algorithms used with them, including insertion, search, deletion, and how they work differently for ordered versus unordered arrays. It covers creating and manipulating arrays procedurally and using classes, and algorithms like linear search, binary search, and shifting elements to insert, delete and make space in the arrays. Key points are that ordered arrays allow faster searching using binary search but slower insertion and deletion due to the need to find the correct position or shift all elements.

Uploaded by

Brian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views22 pages

Data Structures & Algorithms: by L. Mutanu

The document discusses arrays and various algorithms used with them, including insertion, search, deletion, and how they work differently for ordered versus unordered arrays. It covers creating and manipulating arrays procedurally and using classes, and algorithms like linear search, binary search, and shifting elements to insert, delete and make space in the arrays. Key points are that ordered arrays allow faster searching using binary search but slower insertion and deletion due to the need to find the correct position or shift all elements.

Uploaded by

Brian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

DATA STRUCTURES &

ALGORITHMS
By L. Mutanu

CH2: ARRAYS

ARRAYS AS DATA STRUCTURES

An array is the most commonly used data storage structure;

We will examine how the insertion, search, and deletion


algorithms work in arrays

By L. Mutanu

CH2: ARRAYS

REVIEW CREATING ARRAYS PROCEDURAL APPROACH


#include <iostream>
using namespace std;
int main()
{
int arr[100]; //array
arr[0]
arr[1]
arr[2]
arr[3]
arr[4]
arr[5]
arr[6]
arr[7]
arr[8]
arr[9]

=
=
=
=
=
=
=
=
=
=

for(int j=0; j<10; j++) //display items


cout << arr[j] << ;
return 0;
}

77; //insert 10 items


99;
44;
55;
22;
88;
11;
00;
66;
33;

Exercise: Modify the insert method to accept data from the user instead

CH2: ARRAYS

REVIEW CREATING ARRAYS OOP APPROACH


#include <iostream>
using namespace std;
class myArray
{
private:
int v[100]; //array doubles
public:
void insert()
{ v[0]= 77; //insert 10 items
v[1]= 99;
v[2]= 44;
v[3]= 55;
v[4]= 22;
v[5]= 88;
v[6]= 11;
v[7]= 00;
v[8]= 66;
v[9]= 33;
} //array, at index

void display()
{for(int j=0; j<10; j++) //display items
cout << v[j] << " ";
cout << endl;
}
};
int main()
{
myArray arr; //create an object
arr.insert();
arr.display();
return 0;
}

Exercise: Modify the insert method to accept data from the user instead

CH2: ARRAYS

INSERT AND DISPLAY ALGORITHMS

The previous example makes use of two algorithms:


Insert adds an element at the last available space
Display shows all the elements in the array.

These are the simplest array algorithms and are often


introduced when learning arrays.

Search and Delete are slightly more complex. We look at them


next

By L. Mutanu

CH2: ARRAYS

SEARCH ALGORITHMS
1.
2.
3.

Searching calls for receiving an element value to search for (search key).
The search key is compared to each element in the array
Finally a message displayed if it was found or not
bool find(int searchKey) //receive search key
{
for(int j=0; j<10; j++) //compare each element,
if(v[j] == searchKey) //if found
break;
//exit loop before end
if(j == 10) //if end without find
return false;
// return cant find it expression
else
return true; //return found it expression
} //end find()
};

By L. Mutanu

CH2: ARRAYS

COMPLETE PROGRAM
#include <iostream>
using namespace std;
class myArray
{
private:
int v[100]; //array doubles
public:
void insert()
{
v[0]= 77; //insert 10 items
v[1]= 99;
v[2]= 44;
v[3]= 55;
v[4]= 22;
v[5]= 88;
v[6]= 11;
v[7]= 00;
v[8]= 66;
v[9]= 33;
} //array, at index
void display()
{for(int j=0; j<10; j++) //display items
cout << v[j] << " ";
cout << endl;
}

bool find(int searchKey)


{
int j;
for(j=0; j<10; j++)
//for each element,
if(v[j] == searchKey)
//found item?
break;
//exit loop before end
if(j==10)
//ended without find
return false;
// cant find it
else
return true;
//found it
} //end find()
};
int main()
{
myArray arr; //create an object
arr.insert();
arr.display();
if( arr.find(35) )
cout << "Found " << endl;
else
cout << "Cant find " << endl;
return 0;
}
Exercise:
1. Modify the program to ask the user for the search
key
2. What if there were two or more elements equal to
the search key?

CH2: ARRAYS

DELETE ALGORITHM
1.
2.

The delete algorithm is similar to the search because it has to search for the item to delete first.
When it finds that element, it shifts all the elements in higher index cells down one cell, thus
overwriting the deleted value
You can call display() member function again after deleting to confirm
bool remove(int deleteKey)
{
int j;
for(j=0; j<10; j++) //look for it
if( deleteKey == v[j] )
break;
if(j==10) //cant find it
return false;
else //found it
{
for(int k=j; k<10; k++) //move higher ones down
v[k] = v[k+1];
return true;
}
} //end delete()

Exercise: Add the delete function to your program.

CH2: ARRAYS

COMPLETE PROGRAM
#include <iostream>
using namespace std;
class myArray
{
private:
int v[100]; //array doubles
public:
void insert()
{
v[0]= 77; //insert 10 items
v[1]= 99;
v[2]= 44;
v[3]= 55;
v[4]= 22;
v[5]= 88;
v[6]= 11;
v[7]= 00;
v[8]= 66;
v[9]= 33;
} //array, at index
void display()
{for(int j=0; j<10; j++) //display items
cout << v[j] << " ";
cout << endl;
}

bool find(int searchKey)


{
int j;
for(j=0; j<10; j++)
if(v[j] == searchKey)
break;
if(j==10)
return false;
else
return true;
} //end find()

int main()
{
myArray arr; //create an object
arr.insert();
arr.display();
if( arr.find(35) )
cout << "Found " << endl;
else
cout << "Cant find " << endl;
if( arr.remove(55))
cout << "Deleted " << endl;
else
cout << "Cant find " << endl;
arr.display();

bool remove(int deleteKey)


{
int j;
for(j=0; j<10; j++) //look for it
if( deleteKey == v[j] )
return 0;
break;
}
if(j==10) //cant find it
return false;
else //found it
{
for(int k=j; k<10; k++) //move higher ones
down
v[k] = v[k+1];
return true;
}
} //end delete()
};

Exercise: Modify the program to ask the user for a number to delete

CH2: ARRAYS

ORDERED ARRAYS

The ordered array is a special array in which the data is stored in


ascending (or descending) key order.

Ordered arrays increase the speed of searching for data.

Linear search - With unordered arrays the only way to search for data is to go through
each element. This is called a linear search. At best the first element is what you are
searching for. At worst case it at the end thus search time=full array
Binary Search - With ordered arrays you can pick the midpoint of the array and if the
figure you are looking for is higher or lower you only need to move to one side and
pick the midpoint again. Notice this way you dont need to go through the entire array.
You can get lucky and find the search key at the first midpoint. Thus search
time=zero. Or at worst you only need to go through half the array. Thus search
time=half array.

By L. Mutanu

CH2: ARRAYS

BINARY SEARCH ALGORITHM

By L. Mutanu

CH2: ARRAYS

BINARY SEARCH ALGORITHM


1.

Create three variables to mark the


minimum, mid, and maximum array
indexes . The mid can be calculated by
(min+max)/2

2.

Check if mid is the search key. If it is


display found.

3.

If it is not check if search key is above or


below and go to the correct half.

4.

Treat the new half as a new full array and


repeat the process i.e. redefine the new
min (if search key is above-min=mid+1)
or max (if search key is below-max=mid1).

5.

You will know the search key wasnt found


if mid becomes greater than max
overlaps
By L. Mutanu

int find(int searchKey)


{
int lowerBound = 0;
int upperBound = 9;
int curIn;
while(true)
{
curIn = (lowerBound + upperBound ) / 2;
if(v[curIn]==searchKey)
return curIn; //found it
else if(lowerBound > upperBound)
return nElems; //cant find it
else //divide range
{
if(v[curIn] < searchKey)
lowerBound = curIn + 1; //its in upper half
else
upperBound = curIn - 1; //its in lower half
} //end else divide range
} //end while
} //end find()

CH2: ARRAYS

THE COMPLETE PROGRAM


#include <iostream>
using namespace std;
class myArray
{
private:
int v[100]; //array doubles
public:
void insert()
{
v[0]= 11; //insert 10 items
v[1]= 22;
v[2]= 33;
v[3]= 44;
v[4]= 55;
v[5]= 66;
v[6]= 77;
v[7]= 88;
v[8]= 99;
v[9]= 110;
} //array, at index
void display()
{for(int j=0; j<10; j++) //display items
cout << v[j] << " ";
cout << endl;
}

int find(int searchKey)


{
int lowerBound = 0;
int upperBound = 9;
int curIn;
while(true)
{
curIn = (lowerBound + upperBound ) / 2;
if(v[curIn]==searchKey)
return curIn; //found it
else if(lowerBound > upperBound)
return 10; //cant find it
else //divide range
{
if(v[curIn] < searchKey)
lowerBound = curIn + 1; //its in upper half
else
upperBound = curIn - 1; //its in lower half
} }}};//end else , while, find, class
int main()
{
myArray arr; //create an object
arr.insert();
arr.display();
if( arr.find(55) != 10 )
cout << "Found " << endl;
else
cout << "Cant find " << endl;
return 0;
}

Exercise: Modify the program to work with employee names as input

CH2: ARRAYS

INSERT ALGORITHM FOR ORDERED ARRAYS

To insert employee number 750 first perform a linier search to find out
where 750 should go

Create room by shifting the other elements from the end one element
at a time

Insert the employee

CH2: ARRAYS

THE COMPLETE PROGRAM


class myArray
{
private:
int v[100]; //array doubles
public:
void insert(int value) //receive element
{
int j;
for(j=0; j<10; j++) //find where it goes
if(v[j] > value)
//(linear search)
break;
for(int k=10; k>j; k--) //move elements up
v[k] = v[k-1];
v[j] = value; //insert it
} //end insert()
void display()
{for(int j=0; j<10; j++) //display items
cout << v[j] << " ";
cout << endl;
}
};

int main()
{
myArray arr; //create an object
arr.insert(77); //insert 10 items
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.insert(22);
arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);
arr.display();
return 0;
}

Exercise: Modify the program to accept input from the user. Use a loop
Add a delete method for ordered arrays.

CH2: ARRAYS

DELETE ALGORITHM FOR ORDERED


ARRAY

Deleting an element in an
ordered array calls for:
1. Performing a binary search
to find it
2. Pushing every element
after it forward to overwrite
it.

bool remove(int value)


{
int j = find(value); //recall find returns index
if(j==10) //cant find it
return false;
else //found it
{
for(int k=j; k<10; k++) //move bigger ones
down
v[k] = v[k+1];
return true;
}
} //end remove()

By L. Mutanu

Exercise: Write the complete program

CH2: ARRAYS

THE ADVANTAGES OF USING ORDERED ARRAYS

Advantages:

Disadvantages:

Searching is fast

Insertion is slow as we have to find the correct position


Deleting is slow as everything after deleted item has to be moved one
place forward

Thus an ordered array is best for scenarios where searches are


more common than insertions and deletions. E.g. an employee
database. Often data is searched to update a record rather than
hire or fire an employee (insert or delete) a record. An inventory
for a retail store is however not a good database to use an
ordered array as items are added and deleted all the time.

By L. Mutanu

CH2: ARRAYS

EVALUATING DATA STRUCTURES

How many steps are necessary to perform a binary search on a given array? Assume
an array of size 10. Lets pick an index to search :

say 3. We check index 5, then 3, and find it...2 mid pt checks


say 4. We check index 5, then 3, then 4 and find it...3 mid pt checks
say 1. We check index 5, then 3, then 2, then 1, and find it...4 mid pt checks

With a binary search the first and last element take the most checks. For an array of
size 10 any index position can be found with less than 4 checks.

Thus for an array of size 100, index calls for checking a maximum of 50, 25, 12, 6, 3, 2,
and 1...7 checks

For an un ordered array the best case would be if the item is the first in the array and
the worst case would be if the item is the last one. We can assume the average of the
best and worst case to be the average search time in a linear search. Thus an array of
size 10 would take 10/2=5 and array of size 100 would be 100/2=50.or simply N/2

By L. Mutanu

CH2: ARRAYS

We can summarize this as follows:

Note that for small data the difference is not so


significant but as the data increases the speed
of a binary search becomes apparent.
Note also that raising two to the comparisons
(s) needed gives you a value close to the array
size (r). R=2s .

CH2: ARRAYS

If we want to know the number of checks given the array size


we must make s the subject of the formula. Thus:
R=2s s = log2(r)
power

The inverse of raising something to a


is a logarithm

For example log2(100) = 6.644 which rounds off to 7.

By L. Mutanu

CH2: ARRAYS

BIG O NOTATION

When comparing algorithms, you dont really care about the particular
microprocessor chip or compiler; all you want to compare is how T
changes for different array sizes (N).
The Big O notation thus ignores the constant and describes time (T) as
the order of variations of the size (N) denoted by O()
Thus In Big O notation, we would say that a linear search takes O(N)
time (we ignore /2), and a binary search takes O(log N) time. Insertion
into an unordered array takes O(1), or constant time.

We find that Insertion into an unordered array takes the least time,
followed by a binary search and then a linear search takes the most
time.

CH2: ARRAYS

In an unordered array you can insert items quickly, in O(1)


time, but searching is slow O(N) time.

In an ordered array you can search quickly, in O(log N) time,


but insertion takes O(N) time.

For both kinds of arrays, deletion takes O(N) time because half
the items (on the average) must be moved to fill in the hole.

It would be nice if there were data structures that could do


everythinginsertion, deletion, and searchingquickly, ideally
in O(1) time, but if not that fast, then in O(log N) time.

By L. Mutanu

You might also like