Download Stage a 1

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Transcript
KING ABDULAZIZ UNIVERSITY
Faculty of Computing & Information Technology
Department of Computer Science
Lab Manual
CPCS204
Data Structures 1
1432/1433H
Lab - 7
Learning Procedure
1)
Stage J (Journey inside-out the concept)
2)
Stage a1 (apply the learned)
3)
Stage v (verify the accuracy)
4)
Stage a2 (assess your work)
Term I
2011
Lab-7: Recursion
Laboratory 7:
Statement Purpose:
This lab will give you practice with Recursion.
Activity Outcomes:
This lab teaches you the following topics:




Simple recursion
Recursion with a return value.
Binary search (divide and conquer) using recursion.
Recursive implementation of Merge sort
Instructor Note:
As pre-lab activity, review Ch9, from the book Data Structures with Java by
John R. Hubbard and also the relevant instructor’s slides.
Names
I.D.
1. .……………..……………………………….
………………………………
2. ..……………………………………………..
………………………………
3. .……………………………………………...
………………………………
4. .……………………………………………..
..…………………………….
CPCS204 – The Lab Note
Lab-7
1
Term I
2011
Lab-7: Recursion
1) Stage J (Journey)
Recursion: is a programming technique that allows the programmer to express
operations in terms of themselves. In JAVA, this takes the form of a function
that calls itself. A useful way to think of recursive functions is to imagine them
as a process being performed where one of the instructions is to "repeat the
process". This makes it sound very similar to a loop because it repeats the
same code, and in some ways it is similar to looping. On the other hand,
recursion makes it easier to express ideas in which the result of the recursive
call is necessary to complete the task. Of course, it must be possible for the
"process" to sometimes be completed without the recursive call.
Simple example: is the idea of building a wall that is ten feet high; if I want to
build a ten foot high wall, then I will first build a 9 foot high wall, and then add
an extra foot of bricks. Conceptually, this is like saying the "build wall" function
takes a height and if that height is greater than one, first calls itself to build a
lower wall, and then adds one a foot of bricks.
Criteria of Recursion:
Every recursion should have the following characteristics.
1. A simple base case which we have a solution for and a return value.
2. A way of getting our problem closer to the base case. I.e. a way to chop
out part of the problem to get a somewhat simpler problem.
3. A recursive call which passes the simpler problem back into the method.
2) Stage a1 (apply)
Example 1: Factorial Function
Apply and test the simple QUEUE implementation using Circular Arrays below:
You have probably seen the factorial function before. It is defined for all
integers greater or equal to zero:
For example,
factorial( 5 ) = 5 * factorial( 4 )
CPCS204 – The Lab Note
Lab-7
2
Term I
2011
Lab-7: Recursion
= 5 * ( 4 * factorial( 3 ) )
= 5 * ( 4 * (3 * factorial( 2 ) ) )
= 5 * ( 4 * (3 * (2 * factorial( 1 ) ) ) )
= 5 * ( 4 * (3 * (2 * ( 1 * factorial( 0 ) ) ) ) )
= 5 * ( 4 * (3 * (2 * ( 1 * 1 ) ) ) )
= 5 * 4 * 3 * 2 * 1 * 1 = 120
Often factorial(N) is written as N!
factorial( 0 ) = 1 // Base Case
factorial( N ) = N * factorial( N-1 ) // Recursive Case
// Example: Concept of recursion
// To Compute Factorial of any given number
import javax.swing.JOptionPane;
public class ComputeFactorial {
public static void main(String[] args) {
String intString = JOptionPane.showInputDialog("Please
enter a non-negative integer:");
int n = Integer.parseInt(intString);
JOptionPane.showMessageDialog(null, "Factorial of " +
n + " is " + factorial(n));
}
// Recursive Method to solve the factorial of a number
public static long factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1); // Recursive call
}
}
}
Output:
CPCS204 – The Lab Note
Lab-7
3
Term I
2011
Lab-7: Recursion
Activity1:
In order to calculate POWER of given x, y.
We have probably worked out 25 something like this:
20 = 1
We started with the simplest case:
Then we multiplied the previous result by 2:
21 = 2 x 20 = 2
Then we multiplied the previous result by 2:
22 = 2 x 21 = 4
Then we multiplied the previous result by 2:
23 = 2 x 22 = 8
Then we multiplied the previous result by 2:
24 = 2 x 23 = 16
Then we multiplied the previous result by 2:
25 = 2 x 24 = 32
In general,
2n = 2 x 2n-1
provided n is an integer >= 0.
So………….
Now we can write the Java method to return the value of two raised to some
power, n.
Act1_Task: Write and test your java code to solve the above given problem.
Example 2: Binary search
Binary Searching involves searching for an element in an array, where the
items are arranged in ascending or descending order. That means the entries in
the array are sorted. If you want to learn how to write a function that does
this, keep reading.
Algorithm for Binary Search based on the following three cases:
Case 1: If the key is less than the middle element, recursively search the key in
the first half of the array.
Case 2: If the key is greater than the middle element, recursively search the
key in the second half of the array.
Case 3: If the key is equal to the middle element, the search ends with a match.
CPCS204 – The Lab Note
Lab-7
4
Term I
2011
Lab-7: Recursion
Carry on repeating the first two steps until the middle element is equal to the
Key.
// Example: Concept of recursion
// To implement binary search using recursion
import java.util.Scanner;
public class BinarySearchDemo {
public static void main(String[] args) {
//a given array hast to be sorted
int [] arr = {11,12,14,16,27,33,68,75};
//input the target key to search for
System.out.print("Enter the KEY target number for
searching: ");
Scanner in = new Scanner(System.in);
int key = in.nextInt();
//trial to find key in arr using biSearch
int result = biSearch(arr, 0, arr.length-1, key);
if (result == -1)
System.err.println("The target number does not
exist !!!");
else
System.out.println("The target number ("+key+")
exists in index ("+result+") the given array.");
}
public static int biSearch(int[] a, int Li, int Hi, int
x){
if (Li > Hi) {
return -1;
}
int mid = (Li + Hi) / 2;
if (a[mid] == x) {
return mid;
} else if (a[mid] > x) {
CPCS204 – The Lab Note
Lab-7
5
Term I
2011
Lab-7: Recursion
Hi
} else
Li
}
return
= mid - 1;
{
= mid + 1;
biSearch(a, Li, Hi, x);
}
}
Output:
Enter the KEY target number for searching: 27
The target number (27) exists in index (4) the given
array.
Or:
Enter the KEY target number for searching: 55
The target number does not exist !!!
Example 3: Merge sort using recursion
Merge sort is a more efficient sorting algorithm than either selection sort or
bubble sort.
The following are the steps of the merge sort:
1. Split the original list into two halves
2. sort each half (using merge sort)
3. merge the two sorted halves together into a single sorted list
// To implement merge sort using recursion
public class MergeSortClass {
private int[] theArray;
public MergeSortClass(int [] unsortedList){
theArray = unsortedList;
}
public void mergeSort(int[] list, int first, int last) {
if (first == last) // if range is 1,
{
return;
// no use sortin
} else {
// find midpoint
int mid = (first + last) / 2;
// sort low half
mergeSort(list, first, mid); // sort high half
mergeSort(list, mid + 1, last); // merge them
merge(list, first, mid + 1, last);
} // end else
}
CPCS204 – The Lab Note
Lab-7
6
Term I
2011
Lab-7: Recursion
// Merge method that will merge two sorted list (array) into one
sorted array.
private void merge(int[] list, int lowPtr, int highPtr, int
upperBound) {
int j = 0; // workspace index
int lowerBound = lowPtr;
int mid = highPtr - 1;
int n = upperBound - lowerBound + 1; // # of items
while (lowPtr <= mid && highPtr <= upperBound) {
if (theArray[lowPtr] < theArray[highPtr]) {
list[j++] = theArray[lowPtr++];
} else {
list[j++] = theArray[highPtr++];
}
}
while (lowPtr <= mid) {
list[j++] = theArray[lowPtr++];
}
while (highPtr <= upperBound) {
list[j++] = theArray[highPtr++];
}
for (j = 0; j < n; j++) {
theArray[lowerBound + j] = list[j];
}
}
}
// MergeSortDemo.java: is a testing MergeSortClass
public class MergeSortDemo {
public static void main(String[] args) {
int a [] = {5,7,9,23,8,17,3};
MergeSortClass ms = new MergeSortClass(a);
System.out.println("The list before sorting is:");
for(int e:a)
System.out.print(e+"
");
//defining an empty array of size a.length to be used for
sorting
int emptyArr [] = new int [a.length];
ms.mergeSort(emptyArr, 0 , a.length-1);
System.out.println("\nThe list after sorting is:");
for(int e:a)
System.out.print(e+"
");
}
}
Output:
The
5
The
3
list before sorting is:
7
9
23
8
17
3
list after sorting is:
5
7
8
9
17
23
CPCS204 – The Lab Note
Lab-7
7
Term I
2011
Lab-7: Recursion
3) Stage v (verify)
Home activities:
1. Write a recursive method to get sum of all number up to given number.
E.g. Number = 5 Result must be sum (1+2+3+4+5)
2. Write a recursive method to get sum of all even numbers up to given
number.
E.g. Number = 5 Result must be sum (2+4)
3. Write a recursive method to get sum of all odd numbers up to given
number.
E.g. Number = 5 Result must be sum (1+3+5)
4. Write a recursive method to get sum all elements of an array.
E.g. A = [5,5,6,7,8] Result must be sum (5+5+6+7+8)
5. (Printing the digits in an integer reversely) Write a recursive method that
displays an int value reversely on the console using the following header:
public static void reverseDisplay(int value)
For example, reverseDisplay(12345) displays 54321.
4) Stage a2 (assess)
Lab Work:
In each laboratory you are assessed on your work within lab session based on
your participation, discussions and achievement of lab activities. Thus, each lab
has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is
used to evaluate your work. This checklist accounts the following criteria:






Following the lab manual step by step
Answering given questions concisely and precisely
Practicing and implementing given examples correctly
Writing code of required programming tasks
Being focused, positive, interactive and serious during lab session
Asking good questions or answering instructor questions if any
Note: performing given home activities or extra programming is highly
recommended to improve your understanding, capability and programming
skills.
CPCS204 – The Lab Note
Lab-7
8