30
Abstract Data Types:- Firstly, a data type (e.g. integer, string, float, Boolean, etc) allows a programmer to create a variable and tells the computer how to handle the data held in the variable. Data types already installed in a programming language are called native or primitive data types. An Abstract Data Type (ADT) is a collection of primitive data types as defined by the programmer. In certain situations, it is more sensible to use an ADT to hold data instead of a series of, what may appear to be, unrelated single native data types. As a CAPE student, you must be aware of three types of ADTs: Stacks, Queues and Singly Linked List. You do not need to know how to create Linked Lists in C; you must know how to create stacks and queues in C though. Stacks: A stack is an ADT based on the principles of LIFO (Last In First Out). Therefore, the last value entered into the stack will 1

Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Embed Size (px)

DESCRIPTION

I made this study guide in high school for some of my friends. This is information for Upper Form 6 (Grade 12 in the US) students. I hope you find this helpful! *CAPE (Caribbean Advanced Proficiency Examination) is the regional exams that this note is preparing them for.

Citation preview

Page 1: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Abstract Data Types:-

Firstly, a data type (e.g. integer, string, float, Boolean, etc) allows a programmer to create

a variable and tells the computer how to handle the data held in the variable. Data types already

installed in a programming language are called native or primitive data types.

An Abstract Data Type (ADT) is a collection of primitive data types as defined by the

programmer. In certain situations, it is more sensible to use an ADT to hold data instead of a

series of, what may appear to be, unrelated single native data types.

As a CAPE student, you must be aware of three types of ADTs: Stacks, Queues and

Singly Linked List. You do not need to know how to create Linked Lists in C; you must know

how to create stacks and queues in C though.

Stacks:

A stack is an ADT based on the principles of LIFO (Last In First Out). Therefore, the last

value entered into the stack will be the first one to come out of the stack. Values are added to the

stack by the Push operation and values are removed from the stack by the Pop operation. Note

that the values of the stack are not moved up or down by the push and pop operations; instead the

position of the top of the stack changes as an operation is done.

Queues:

A queue is an ADT based on the principles of FIFO (First In First Out). Therefore, the

first valued entered into the queue will be the first on to come out of the queue. Values are added

to the queue by the Enqueue operation and values are removed from the queue by the Dequeue

1

Page 2: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

operation. Like stacks, the values are not moved itself but the position of the top of the queues

changes.

Singly Linked List:

A linked list is an ADT which is similar to an array in that a plethora of values can be

stored. It is different from an array in such that an array allocates memory for all its members as

one block of memory whereas, a linked list allocates memory space for each “linked list

element” or “node” and has pointers which are used to link one node to the other – thus creating

a chain link of nodes. Values are added to the list by the Insert function and are removed from

the list by the Delete function.

2

Page 3: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Searching and Sorting:-

For CAPE purposes, you must be aware of two types of sorting and two types of

searching for use with a one-dimensional array. The types of sorting are: simple selection sort

and bubble sort. The types of searching are: linear search and binary search.

Simple Selection Sort:

This is the simplest kind of sorting. This algorithm works as follows:

1. Finds the lowest/highest value of the list

2. Swaps it with the value in the first position

3. Repeats this process starting with the first position as position two, then as position three,

position four,…, till the (n – 1)th position where the array would be completely sorted.

*’n’ is the number of elements in the array

The following algorithm shows the selection sort organising members of an array of numbers

from lowest to highest:

______________________________________________________________________________

// ‘n’ is any value that tells how many elements the array “arr” can hold

int arr[n], count, i, min, temp

/*we are assuming the array has been filled with values already, if not, use a for loop to input

values into the array*/

For count = 1 to (n – 1) step 1

min = count //let the variable min start at 1

3

Page 4: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

For i = (count + 1) to n step 1

If (arr[i] < arr[min]) /*if the current value of the array is less than the smallest

value of the array then,*/

min = i //give min the current value of i (the new smallest value)

End if

End for

/*the following three lines swaps the lowest value of the array to the first position in the

first iteration, second position in the second iteration, and so on.*/

temp = arr[count] //the temporary variable take the value of arr[count]

arr[count] = arr[min] // arr[count] takes the value of arr[min]

arr[min] = temp //arr[min] takes the value of temp

End for

______________________________________________________________________________

So let’s try to understand the algorithm is doing. We have an array of integers with

elements {23, 12, 37, 16, 25, 18} and we would like to sort them in ascending order. So, for i = 2

to 6, check to see if the current value of the array (i = 2) is less than the first value of the array

(min). Is 12 less than 23? Yes! So, ‘min’ becomes position 2 (i.e. so far the value of the element

in position 2 is the lowest in the array). The algorithm continues looping to ensure that 12 is the

lowest number in the array. In this case it is. If it was not, min would take the position of the

element with the lowest value most recently found. Then the swapping takes place. In our

example, the value 23 is given to the ‘temp’ variable, the value 12 is given to the first location of

the array, and the value 23 is given to the second location of the array. The array now looks like

4

Page 5: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

this: {12, 23, 37, 16, 25, 18}. Now, this for loop (the one using the variable ‘i’) checks to see if

there is any value in the array smaller than the first. Thus, at the end of the first outer loop, the

smallest value of the array will be at the first location of the array. After that, count starts at 2 so,

the algorithm will loop until the second smallest value is in the second location and so it goes.

So we see that this is a simple way to sort an array. We also see that this is a very long

way to sort an array thus, may use large amounts of processing power on large databases. Even if

the array is sorted after the first iteration, the algorithm continues until the outer for loop finishes.

In the case where an array may have been partially sorted, it is better to use the bubble sort.

5

Page 6: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Bubble Sort:

The bubble sort is a more efficient sort than the selection short in that if no values are

swapped the algorithm is terminated, saving processing power from the computer and time for

the user. The purpose of this algorithm is to “bubble” the largest value to the first/last place of

the array.

The following algorithm shows the bubble sort organising members of an array of numbers from

lowest to highest:

______________________________________________________________________________

// ‘n’ is any value that tells how many elements the array “arr” can hold

int arr[n], i, temp

boolean flag

/*we are assuming the array has been filled with values already, if not, use a for loop to input

values into the array*/

Do

flag = false /*flag is false to signal that the array is sorted. We assume this at the first

round*/

For i = 1 to (n – 1) step 1

If (arr[i] > arr[i + 1] /*swap the values if the value at the current position is

greater than the value at the next position*/

temp = arr[i]

arr[i] = arr[i + 1]

arr[i + 1] = temp

flag = true //set flag to true so the (do..while) loop will continue

6

Page 7: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

End if

End for

n = n – 1

While (flag == true)

______________________________________________________________________________

So, let’s try to understand this algorithm. We’ll use the same array of integers as last

time: {23, 12, 37, 16, 25, 18} and we would like to sort them in ascending order. For i = 1 to 5,

check to see if the current value of the array at ‘i’ (1) is greater than the value of the array at ‘i +

1’ (2). Is 23 greater than 12? Yes! So swap the values of the array and set the flag to true. The

array would now look like: {12, 23, 37, 16, 25, 18}. Now, for i = 2 to 5, check to see if the

current value of the array at ‘i’ (2) is greater than the value of the array at ‘i + 1’ (3). Is 23 greater

than 37? No! So nothing is swapped. The third iteration starts and checks to see if 37 is greater

than 16. So it swaps those values. Then, is 37 greater than 25? Yes! So the values are swapped.

The same is done for the last value of the array. Now, the array looks like this: {12, 23, 16, 25,

18, 37}. We see that the largest value of the array has been “bubbled” to the last position of the

array. After the for loop we set the value n to (n – 1). This is done because the last value is the

largest value, we do not need to compare it again! Thus, the amount of time the loop takes is

shortening. As flag == true, the outer loop continues and this process is done again. When all

values are in their right place, ‘flag’ would retain its setting of false and the loop will close.

7

Page 8: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Sequential Search:

The easiest way to search a record is by using the sequential/linear/serial sort. It simply

checks all the elements of the array with the value the user want to find and returns it when

found.

The following algorithm shows a sequential search throughout an array to find the index of the

search key. If it is not found, the algorithm returns -1:

______________________________________________________________________________

// ‘n’ is any value that tells how many elements the array “arr” can hold

int arr[n], count, searchKey

boolean found

/*we are assuming the array has been filled with values already, if not, use a for loop to input

values into the array*/

found = false

For count = 1 to n step 1

//this part checks to see if the value is in the array at position ‘count’

If (searchKey == arr[count])

return count //return the value of count to the computer

found = true //set the value of found to true

break //break or stop the loop as the value was found

End if

End for

If (found == false) //if the value was not found then,

8

Page 9: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

return -1

End if

______________________________________________________________________________

This algorithm truly is simple. Firstly, set the value of ‘found’ to false as the value was

not found in the array. Then, start the loop from 1 to the last value of the array. Use the If

statement to compare values. If the value was found, return the value of count (the position of

the array), set ‘found’ to true and break/stop the loop. If the value was not found, then the value

of ‘found’ would remain false. So, if found == false, return -1.

The obvious problem is that if the value to be found is at the end of the array, this

processing is a time consuming process. Therefore, for large databases, this is not a

recommended searching procedure. On the other hand, we can use the binary search – a much

more efficient searching algorithm given that the array is sorted.

9

Page 10: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Binary Search:

Once an array is sorted, a fast search can be done. Let’s consider a sorted array of

numbers. The user then types a value to search for. Now if the value of the search key is bigger

than the value of the number in the middle position of the array, do we need to check the values

of the first half? No! The arrays are sorted so the numbers in the first half is smaller than the

number in the middle position. So we shorten the amount of elements we need to search. This

elimination process is done until the desired value of the array is found.

The following algorithm shows a binary search throughout an array to find the index of the

search key. If it is not found, the algorithm returns -1:

______________________________________________________________________________

// ‘n’ is any value that tells how many elements the array “arr” can hold

int arr[n], searchKey, mid, first

boolean found = false

/*we are assuming the array has been filled with values already, if not, use a for loop to input

values into the array*/

first = 1

Do

mid = (first + n) / 2 //mid is the integer average of the first and last positions of arr

If (searchKey > arr[mid]) /*if the value of searchKey is bigger than the value at the

middle position of arr then,*/

first = mid + 1

10

Page 11: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Else if (searchKey < arr[mid] /*if the value of searchKey is less than the value at the

middle position of arr then,*/

n = mid – 1

//if the value is equal to arr[mid] then,

Else

return mid

found = true

break

While (first < n)

If (found == false)

return -1

______________________________________________________________________________

Once again, please be reminded that this algorithm works only if the array is sorted!

Firstly, set ‘found’ to false as the search key has not been found yet. After assigning the value of

mid, check to see if the search key is greater than, less than or equal to the value of arr[mid].

When it is equal to arr[mid], the index is returned, found is set to true and the loop breaks. If it is

greater than arr[mid], the first number is reassigned to ‘mid + 1’. If it less than arr[mid], the last

number is reassigned to ‘mid – 1’. Thus, as the loop is reiterated, the new value of mid disallows

the algorithm to search elements of a smaller/larger value. For example, we have an array with

10 spaces. The user types in a search key, and it is in position 2 (the program does not know this

as yet). Now, mid is originally (10 + 1) / 2 = 5.5 Wrong! It is 5 because an integer value ignores

the point and everything after it. The value of the search key would be less than the value of the

element in position 5. So, the algorithm makes the last value of the array 4 (i.e. mid – 1). Thus,

11

Page 12: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

as found is still false and first (1) is less than last (4), the loop is done again. The value of mid

becomes (1 + 4) / 2 = 2, which is the location with the search key! So, the value of mid is

returned, found is set to true and the loop breaks.

12

Page 13: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

C Code

Selection Sort

______________________________________________________________________________

void selectionSort (int array[], int n){

int pass, i, temp, potSmall;

for (pass = 0; pass < n - 1; pass++){

potSmall = pass; //assume this element is the smallest

//hook over the rest of elements to find smallest

for (i = pass + 1; i < n; i++){

if (array[i] < array[potSmall]){

potSmall = i; //Remember the location of new found smallest

} //end if

} //end for

//swap smallest remaining element

temp = array[pass];

array[pass] = array[potSmall];

array[potSmall] = temp;

} //end for

} //end method

______________________________________________________________________________

13

Page 14: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Bubble Sort

______________________________________________________________________________

void bubbleSort (int array[], int n){

int pass, i, temp;

for(pass = 1; pass < n; pass++){

for(i = 0; i < n - pass; i++){

if(array[i] > array[i + 1]){

temp = array[i];

array[i] = array[i + 1];

array[i + 1] = temp;

} //end if

} //end for

} //end for

} //end method

______________________________________________________________________________

14

Page 15: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Sequential Search

______________________________________________________________________________

int linearSearch (int array[], int first, int last, int key){

int i, flag;

flag = 1;

for (i = first; i <= last; ++i){

if (key == array[i]){

return i;

flag = 0;

break;

} //end if

} //end for

if (flag = 1)

return -1;

} //end method

______________________________________________________________________________

15

Page 16: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Binary Search

______________________________________________________________________________

int binarySearch (int sortedArray[], int first, int last, int key){

int mid = 0, flag;

flag = 1;

while (first < last){

mid = (first / last) / 2;

if (key > sortedArray[mid])

first = mid + 1;

else if (key < sortedArray[mid])

last = mid - 1;

else{

return mid;

flag = 0;

break;

} //end else

} //end while loop

if (flag == 1)

return -1;

} //end method

______________________________________________________________________________

16

Page 17: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

**Pop Stack (assuming there are 100 elements in the integer array, empty spaces = -99)

______________________________________________________________________________

int popStack (int stack[], int top){ //’top’ is the index of the last element entered

int value;

//check for error situation first

if (top < 0){

printf(“The stack is already empty”);

return -1;

} //end if

else if (top > 99){

printf (“Elements size is beyond the stack size”);

return -1;

} //end if

else{ //stack can be popped

value = stack[top];

stack[top] = -99;

top = top – 1;

return value;

} //end else

} //end method

______________________________________________________________________________

17

Page 18: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Push Stack (assuming there are 100 elements in the integer array, empty spaces = -99)

______________________________________________________________________________

void pushStack (int stack[], int top, int value){ //’top’ is the index of the last element entered

//check for error situation first

if (top < 0)

printf (“Invalid index was entered”);

else if (top == 99)

printf (“The stack is already full”);

else if (top > 99)

printf (“Element size is beyond the stack size”);

else {

if (top != 0)

top = top + 1;

stack [top] = value;

} //end else

} //end method

______________________________________________________________________________

18

Page 19: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

**Dequeue Queue (assuming there are 100 elements in the integer array, empty spaces = -99)

______________________________________________________________________________

int dequeue (int queue[]){

int value;

//check for error situation first

if (queue[0] == -99){

printf (“The queue is already empty”);

return -1;

} //end if

else{ //queue can be dequeued

value = queue[0];

//shift all the elements one place up

for (int x = 0; queue[x] != -99 && x < 100; x++){

queue[x] = queue[x+1];

} //end for loop

queue[99] = -99;

return value;

} //end else

} //end method

______________________________________________________________________________

19

Page 20: Introduction to Basic Abstract Data Types, Search and Sort Algorithms

Enqueue Queue (assuming there are 100 elements in the integer array, empty spaces = -99)

______________________________________________________________________________

void enqueue (int queue[], int tail, int value){

//check for error situation first

if (tail < 0)

printf (“Invalid tail of queue”);

else if (tail == 99)

printf (“The queue is already full”);

else if (tail > 99)

printf (“Element size is beyond queue size”);

else { //queue can be enqueued

if (tail != 0)

tail = tail + 1;

queue [tail] = value;

} //end else

} //end method

______________________________________________________________________________

20