introduction

80

Upload: lisle

Post on 05-Jan-2016

30 views

Category:

Documents


1 download

DESCRIPTION

Section 13.1. Introduction. Algorithm Definition. An algorithm is a step-by-step solution to a problem. Niklaus Wirth’s Programming Language Definition. Niklaus Wirth , the creator of the programming language Pascal , made the following equation about data structures and algorithms. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction
Page 2: Introduction

Algorithm Definition

An algorithm is a step-by-step solution to a problem.

Page 3: Introduction

Niklaus Wirth’s Programming Language

Definition

Niklaus Wirth, the creator of the programming language Pascal, made the following equation about data structures and algorithms.

Data Structures + Algorithms = Programs

Page 4: Introduction

Algorithm Example:Find the average of 5 numbers

1. Enter 5 numbers.

2. Add them and store the total.

3. Divide the total by 5. The result is the average.

4. Display the average.

Page 5: Introduction
Page 6: Introduction

When is a Random# not a Random#?This section will seem somewhat strange.

You are going to learn how to generate random numbers that are not random.

It probably sounds quite weird, but later in the chapters you will see good reasons for controlling the random numbers.  Right now for starters let us review generating true random integers with the Expo.random(min,max) method.

Page 7: Introduction

// Java1301.java// This program reviews generating random numbers with the <Expo.random> method.

public class Java1301{

public static void main(String args[]){

System.out.println("\nGenerating numbers in the [10..99] range\n");for (int k = 0; k < 100; k++){

int randInt1 = Expo.random(10,99);System.out.print(randInt1 + " ");

}System.out.println("\n\n");

System.out.println("\nGenerating numbers in the [100..999] range\n");for (int k = 0; k < 100; k++){

int randInt2 = Expo.random(100,999);System.out.print(randInt2 + " ");

}System.out.println("\n\n");

System.out.println("\nGenerating numbers in the [1000..9999] range\n");for (int k = 0; k < 100; k++){

int randInt3 = Expo.random(1000,9999);System.out.print(randInt3 + " ");

}System.out.println("\n\n");

} }

Page 8: Introduction
Page 9: Introduction
Page 10: Introduction

// Java1302.java// This program introduces the <Random> class and the <nextInt> method. The <nextInt> method // generates a random integer in the [0..n-1] range, if n is the integer parameter passed to <nextInt>.

import java.util.Random;

public class Java1302{

public static void main(String args[]){

Random rand = new Random();

System.out.println("\nGenerating numbers in the [0..99] range\n");for (int k = 0; k < 100; k++){

int randInt1 = rand.nextInt(100);System.out.print(randInt1 + " ");

}System.out.println("\n\n");

System.out.println("\nGenerating numbers in the [0..999] range\n");for (int k = 0; k < 100; k++){

int randInt1 = rand.nextInt(1000);System.out.print(randInt1 + " ");

}System.out.println("\n\n");

System.out.println("\nGenerating numbers in the [0..9999] range\n");for (int k = 0; k < 100; k++){

int randInt1 = rand.nextInt(10000);System.out.print(randInt1 + " ");

}System.out.println("\n\n");

} }

Page 11: Introduction
Page 12: Introduction
Page 13: Introduction

Random Class and nextInt Method

Java has a Random class to generate random integers.An object must be constructed first like: 

Random rand = new Random(); Random integers are then generated with method nextInt, like  

int n1 = rand.nextInt(100); // random int in [0..99] range

int n2 = rand.nextInt(500); // random int in [0..499] range

int n3 = rand.nextInt(n); // random int in [0..n-1] range

Page 14: Introduction

// Java1303.java// This program shows that the <Random> object, like all objects, can be any name, and frequently // the lower-case class name is used. It also shows how to control the random integer range.

import java.util.Random;

public class Java1303{

public static void main(String args[]){

Random random = new Random();

System.out.println("\nGenerating numbers in the [10..99] range \n");for (int k = 0; k < 100; k++){

int randInt1 = random.nextInt(90) + 10;System.out.print(randInt1 + " ");

}System.out.println("\n\n");

System.out.println("\nGenerating numbers in the [100..999] range \n");for (int k = 0; k < 100; k++){

int randInt1 = random.nextInt(900) + 100;System.out.print(randInt1 + " ");

}System.out.println("\n\n");

System.out.println("\nGenerating numbers in the [1000..9999] range \n");for (int k = 0; k < 100; k++){

int randInt1 = random.nextInt(9000) + 1000;System.out.print(randInt1 + " ");

}System.out.println("\n\n");

} }

Page 15: Introduction
Page 16: Introduction
Page 17: Introduction

Random Integer Algorithm1. Determine how many different integers will be

generated, called the range, which is done using:

int range = max - min + 1; 2. Use the range value in the parameter of nextInt, like:

int randomInt = rand.nextInt(range); 3. Add the minimum value to step 2, like:

int randomInt = rand.nextInt(range) + min;

Page 18: Introduction

// Java1304.java// In this program the program user is able to enter the minimum // and the maximum integer value of the random number range.// Essentially, the program now behaves like the <Expo.random> method.

import java.util.Random;

public class Java1304{

public static void main(String args[]){

Random random = new Random();

System.out.print("Enter minimum random integer ===>> ");int min = Expo.enterInt();System.out.print("Enter maximum random integer ===>> ");int max = Expo.enterInt();

int range = max - min + 1;

System.out.println("\nGenerating numbers in the ["+min+".."+max+"] range\n");for (int k = 0; k < 100; k++){

int randomInt = random.nextInt(range) + min;System.out.print(randomInt + " ");

}System.out.println("\n\n");

} }

Page 19: Introduction
Page 20: Introduction

// Java1305.java// A small, but significant change is made in this program. In line-13 the <Random> // constructor now has a parameter value. The result is that each time the random // number set will be identical. This is called a "RANDOM SEED".

import java.util.Random;

public class Java1305{

public static void main(String args[]){

Random random = new Random(12345); // Note the different constructor

System.out.print("Enter minimum random integer ===>> ");int min = Expo.enterInt();System.out.print("Enter maximum random integer ===>> ");int max = Expo.enterInt();

System.out.println("\nGenerating numbers in the ["+min+".."+max+"] range\n");for (int k = 0; k < 100; k++){

int range = max - min + 1;int randomInt = random.nextInt(range) + min;System.out.print(randomInt + " ");

}System.out.println("\n\n");

} }

Page 21: Introduction
Page 22: Introduction

How Is This Useful?Example. At Rubix Cube competitions, every contestant’s cube is scrambled the exact same way in order to be completely fair.

If the contest was done on computerwith a Rubix Cube Simulator, it would make sense that the computer randomly

scrambles the cube, but to be fair, every cube needs to be scrambled the exact same way!

Page 23: Introduction

// MyRandom.java// This class is an example of a user-defined class that// simplifies operating with some Java class, like <Random>.

import java.util.Random;

public class MyRandom{

private Random random;

public MyRandom() { random = new Random(); }

public MyRandom(int seed) { random = new Random(seed); }

public int nextRandom(int min, int max){

int range = max - min + 1;int randomInt = random.nextInt(range) + min;return randomInt;

} }

Page 24: Introduction

// Java1306.java// This program tests the user-defined <MyRandom> class.// The first group of numbers will be different in both executions.// The second group of numbers will be identical in both executions.public class Java1306{

public static void main(String args[]){

System.out.print("Enter minimum random integer ===>> ");int min = Expo.enterInt();System.out.print("Enter maximum random integer ===>> ");int max = Expo.enterInt();

MyRandom rand1 = new MyRandom();System.out.println("\nGenerating true random numbers in the ["+min+".."+max+"] range\n");for (int k = 0; k < 100; k++){

int randomInt = rand1.nextRandom(min,max);System.out.print(randomInt + " ");

}System.out.println("\n\n");

MyRandom rand2 = new MyRandom(1234);System.out.println("\nGenerating pseudo random numbers in the ["+min+".."+max+"] range\n");for (int k = 0; k < 100; k++){

int randomInt = rand2.nextRandom(min,max);System.out.print(randomInt + " ");

}System.out.println("\n\n");

} }

Page 25: Introduction
Page 26: Introduction

Truly Random & Pseudo Random

Truly Random Values 

Random rand1 = new Random();  

Pseudo Random Values 

Random rand2 = new Random(12345);  

The parameter value used in the Random constructor is the starting seed of the random number generation. The same sequence of integers will be generated every time the same starting seed value is used.

Page 27: Introduction
Page 28: Introduction

The List Class Case StudyBack in Chapter 11, Arrays were introduced. However, we had our arrays separate from the methods. This is not in the true flavor of OOP Encapsulation.

Before we get too involved with Algorithms, we will create and build a List class. The creation of a List class allows storage of array elements along with the actions or methods that process the array.  In this chapter you will learn some of the common algorithms used in computer science.

These algorithms are independent of a programming language.

The syntax implementation in sample programs may be specific to Java, but the algorithmic considerations carry across all program languages. The List case study will grow with each new algorithm.

Page 29: Introduction

// Java1307.java // List case study #1// The first stage of the List case study  public class Java1307{

public static void main(String args[]){

List1 array1 = new List1(15);array1.display();List1 array2 = new List1(15,999); array2.display();array2.assign();array2.display();System.out.println();

}}

Page 30: Introduction

class List1{

private int intArray[]; // stores array elementsprivate int size; // number of elements in the array

public List1(int s){

System.out.println("\nCONSTRUCTING NEW LIST OBJECT WITH DEFAULT VALUES");size = s;intArray = new int[size];

}

public List1(int s, int n){

System.out.println("\nCONSTRUCTING NEW LIST OBJECT WITH SPECIFIED VALUES");size = s;intArray = new int[size];for (int k = 0; k < size; k++)

intArray[k] = n;}

public void assign(){

System.out.println("\nASSIGNING RANDOM VALUES TO LIST OBJECT");MyRandom rand = new MyRandom(12345);for (int k = 0; k < size; k++)

intArray[k] = rand.nextRandom(1000,9999);}

public void display(){

System.out.println("\nDISPLAYING ARRAY ELEMENTS");for (int k = 0; k < size; k++)

System.out.print(intArray[k] + " ");System.out.println();

} }

Page 31: Introduction
Page 32: Introduction
Page 33: Introduction

// Java1308.java List case study #2// This stage adds a third constructor, which instantiates an array object with// a specified set of random numbers. Old methods, like the first two constructors,// which are not tested are removed for better program brevity and clarity.

public class Java1308{

public static void main(String args[]){

List2 array1 = new List2(15,0,100);array1.display();List2 array2 = new List2(15,100,999);array2.display();List2 array3 = new List2(15,0,1);array3.display();List2 array4 = new List2(15,500,505);array4.display();System.out.println();

}}

Page 34: Introduction

class List2{

private int intArray[ ]; // stores array elementsprivate int size; // number of elements in the arrayprivate int minInt; // smallest random integer private int maxInt; // largest random integer

public List2(int s, int min, int max){

size = s;System.out.println("\nCONSTRUCTING LIST WITH VALUES in ["

+ min + ".." + max + "] range"); intArray = new int[size];MyRandom rand = new MyRandom(12345);for (int k = 0; k < size; k++)

intArray[k] = rand.nextRandom(min,max);}

public void display(){

System.out.println("\nDISPLAYING ARRAY ELEMENTS");for (int k = 0; k < size; k++)

System.out.print(intArray[k] + " ");System.out.println();

} }

Page 35: Introduction
Page 36: Introduction

// Java1309.java List case study #3// This program uses <Expo.pause>, which freezes output display until// the Enter key is pressed. This method allows output viewing on the// monitor when the display becomes too large.

public class Java1309{

public static void main(String args[]){

List3 array1 = new List3(60,100,200);array1.display();Expo.pause();

List3 array2 = new List3(100,100,999);array2.display();Expo.pause();

List3 array3 = new List3(200,10,19);array3.display();Expo.pause();

List3 array4 = new List3(40,500,505);array4.display();Expo.pause();System.out.println();

}}

Page 37: Introduction
Page 38: Introduction
Page 39: Introduction
Page 40: Introduction
Page 41: Introduction

// Java1310.java List case study #4// This program allows all list information to be entered at the keyboard// before a list object is constructed.

public class Java1310{

public static void main(String args[]){

System.out.print("\nEnter list size ===>> ");int listSize = Expo.enterInt();System.out.print("Enter minimum value ===>> ");int listMin = Expo.enterInt();System.out.print("Enter maximum value ===>> ");int listMax = Expo.enterInt();List4 array = new List4(listSize,listMin,listMax);array.display();Expo.pause();System.out.println();

}}

Page 42: Introduction
Page 43: Introduction
Page 44: Introduction

// Java1311.java List case study #5// This program introduces the "inefficient" Linear Search algorithm. 

public class Java1311{

public static void main(String args[]){

System.out.print("\nEnter list size ===>> ");int listSize = Expo.enterInt();System.out.print("Enter minimum value ===>> ");int listMin = Expo.enterInt();System.out.print("Enter maximum value ===>> ");int listMax = Expo.enterInt();List5 array = new List5(listSize,listMin,listMax);array.display();Expo.pause();System.out.print("\nEnter search number ===>> ");int searchNumber = Expo.enterInt();if (array.linearSearch(searchNumber))

System.out.println(searchNumber + " is in the list");else

System.out.println(searchNumber + " is not in the list");System.out.println();

}}

Page 45: Introduction

public boolean linearSearch(int sn){ boolean found = false; for (int k = 0; k < size; k++)

if (intArray[k] == sn) found = true;

return found;}

The Inefficient Linear Search

There are 2 problems with this algorithm:

1) It will keep searching to the end even if it has already found the desired item.

2) When an item is found, it does not tell you where it is.

Page 46: Introduction
Page 47: Introduction
Page 48: Introduction

// Java1312.java List case study #6// The inefficient linear search is replaced with a conditional loop, which stops// the repetition once the searchNumber is found. public class Java1312{

public static void main(String args[]){

System.out.print("\nEnter list size ===>> ");int listSize = Expo.enterInt();System.out.print("Enter minimum value ===>> ");int listMin = Expo.enterInt();System.out.print("Enter maximum value ===>> ");int listMax = Expo.enterInt();List6 array = new List6(listSize,listMin,listMax);array.display();Expo.pause();System.out.print("\nEnter search number ===>> ");int searchNumber = Expo.enterInt();if (array.linearSearch(searchNumber))

System.out.println(searchNumber + " is in the list");else

System.out.println(searchNumber + " is not in the list");System.out.println();

}}

Page 49: Introduction

public boolean linearSearch(int sn){ boolean found = false; int k = 0; while (k < size && !found) {

if (intArray[k] == sn) found = true;else k++;

} return found;}

An Efficient Linear Search

This algorithm does stop when the desired element is found, but it still does not tell us where it is.

Page 50: Introduction
Page 51: Introduction
Page 52: Introduction

// Java1313.java List case study #7// This program makes the Linear Search algorithm more practical// by returning the index of the SearchNumber or -1 if not found.public class Java1313{

public static void main(String args[]){

System.out.print("\nEnter list size ===>> ");int listSize = Expo.enterInt();System.out.print("Enter minimum value ===>> ");int listMin = Expo.enterInt();System.out.print("Enter maximum value ===>> ");int listMax = Expo.enterInt();List7 array = new List7(listSize,listMin,listMax);array.display();Expo.pause();System.out.print("\nEnter search number ===>> ");int searchNumber = Expo.enterInt();int index = array.linearSearch(searchNumber);if (index == -1)

System.out.println(searchNumber + " is not in the list");else

System.out.println(searchNumber + " is found at index " + index);System.out.println();

}}

Page 53: Introduction

public int linearSearch(int sn){ boolean found = false; int k = 0; while (k < size && !found) {

if (intArray[k] == sn) found = true;else k++;

} if (found)

return k; else

return -1;}

An Efficient and Practical Linear Search

Like the last one, this algorithm does stop when the desired element is found.

However, instead of merely returning a boolean, which only told us if it was found, this algorithm returns an int, which tells us the index of where it was found.

It is a convention to return an index of -1 when the desired data is not found.

Page 54: Introduction
Page 55: Introduction
Page 56: Introduction
Page 57: Introduction

Sorting:Why do we sort?

Sorting does not exist in a vacuum.

The reason for sorting is to allow more efficient searching.

Page 58: Introduction

45 is greater than 32; the two numbers need to be swapped.

45 is greater than 28; the two numbers need to be swapped.

45 is not greater than 57; the numbers are left alone.57 is greater than 38; the two numbers need to be swapped.

One pass is now complete. The largest number, 57, is in the correct place.

The Bubble Sort – 1st Pass

45 32 28 57 38

32 45 28 57 38

32 28 45 57 38

32 28 45 38 57

Page 59: Introduction

32 is greater than 28; the two numbers need to be swapped.

32 is not greater than 45; the numbers are left alone.45 is greater than 38; the two numbers need to be swapped.

We can see that the list is now sorted. Our current algorithm does not realize this.All the computer knows is the last 2 numbers are in the correct place.Because of this, it is not necessary to compare 45 and 57.

The Bubble Sort – 2nd Pass

32 28 45 38 57

28 32 45 38 57

28 32 38 45 57

Page 60: Introduction

28 is not greater than 32; the numbers are left alone.32 is not greater than 38; the numbers are left alone.

The 3rd pass is complete, and 38 is “known” to be in the correct place.The 4th pass begins.28 is not greater than 32; the numbers are left alone.

The 4th pass is complete, and 32 is “known” to be in the correct place.A 5th pass is not necessary. 28 is the only number left.

With 5 numbers there will be 4 comparison passes.With N numbers there will be N-1 comparison passes.

The Bubble Sort – 3rd & 4th Pass28 32 38 45 57

28 32 38 45 57

28 32 38 45 57

28 32 38 45 57

Page 61: Introduction

Compare adjacent array elements.Swap the elements if they are not ordered correctly.

Continue this process until the largest element is in the last element of the array.

Repeat the comparison process in the same manner.

During the second pass make one less comparison,and place the second-largest number in the second-to-last element of the array.

Repeat these comparison passes with N elements,N-1 times. Each pass makes one less comparison.

Bubble Sort Logic

Page 62: Introduction

// Java1314.java List case study #8// This program introduces a "partial-sort" algorithm.// Only the largest number is places at the end of the list. 

public class Java1314{

public static void main(String args[]){

System.out.print("\nEnter list size ===>> ");int listSize = Expo.enterInt();System.out.print("Enter minimum value ===>> ");int listMin = Expo.enterInt();System.out.print("Enter maximum value ===>> ");int listMax = Expo.enterInt();

 

List8 array = new List8(listSize,listMin,listMax);array.display();Expo.pause();array.partialSort();array.display();System.out.println();

}}

Page 63: Introduction

public void partialSort(){ int temp; for (int q = 0; q < size-1; q++)

if (intArray[q] > intArray[q+1]){ temp = intArray[q]; intArray[q] = intArray[q+1]; intArray[q+1] = temp;}

}

The Partial Sort

The Partial Sort accomplishes the 1st Pass of the Bubble Sort.

Page 64: Introduction
Page 65: Introduction

// Java1315.java List case study #9// This program sorts in ascending order using the BubbleSort.// This version of the BubbleSort is very inefficient.// It compares numbers that are already the correct location. 

import java.util.*; 

public class Java1315{

public static void main(String args[]){

System.out.print("\nEnter list size ===>> ");int listSize = Expo.enterInt();System.out.print("Enter minimum value ===>> ");int listMin = Expo.enterInt();System.out.print("Enter maximum value ===>> ");int listMax = Expo.enterInt();List9 array = new List9(listSize,listMin,listMax);array.display();Expo.pause();array.bubbleSort();array.display();System.out.println();

}}

Page 66: Introduction

The Bubble Sort

The Bubble Sort gets its name because the larger numbers seem to float to the top (or end) of the array like bubbles.

public void bubbleSort(){ int temp; for (int p = 1; p < size; p++)

for (int q = 0; q < size-1; q++) if (intArray[q] > intArray[q+1]) {

temp = intArray[q];intArray[q] = intArray[q+1];intArray [q+1] = temp;

}}

Page 67: Introduction
Page 68: Introduction

// Java1316.java List case study #10// This program introduces the private <swap> method that is used by the // <bubbleSort> and other methods. It also improves the bubbleSort by // reducing the number of comparison made on each pass. 

import java.util.*;

public class Java1316{

public static void main(String args[]){

System.out.print("\nEnter list size ===>> ");int listSize = Expo.enterInt();System.out.print("Enter minimum value ===>> ");int listMin = Expo.enterInt();System.out.print("Enter maximum value ===>> ");int listMax = Expo.enterInt();List10 array = new List10(listSize,listMin,listMax);array.display();Expo.pause();array.bubbleSort();array.display();System.out.println();

}}

Page 69: Introduction

private void swap(int x, int y){

int temp = intArray[x];intArray[x] = intArray[y];intArray[y] = temp;

}

public void bubbleSort(){

for (int p = 1; p < size; p++)for (int q = 0; q < size-p ; q++)

if (intArray[q] > intArray[q+1])swap(q,q+1);

}

Improved Bubble Sort

If you turn this operator around, it will sort in descending order.

Page 70: Introduction
Page 71: Introduction

Binary Searchwith a Telephone BookStart with a 2000 page telephone book.

Split in two, and ignore 1000 pages and search in the remaining 1000 pages.

Split in two, and ignore 500 pages and search in the remaining 500 pages.

Split in two, and ignore 250 pages and search in the remaining 250 pages.

Split in two, and ignore 125 pages and search in the remaining 125 pages.

Split in two, and ignore 62 pages and search in the remaining 62 pages.

Split in two, and ignore 31 pages and search in the remaining 31 pages.

Split in two, and ignore 15 pages and search in the remaining 15 pages.

Split in two, and ignore 7 pages and search in the remaining 7 pages.

Split in two, and ignore 3 pages and search in the remaining 3 pages.

Split in two, and ignore 1 page and search in the remaining 1 page.

Page 72: Introduction

Binary Search LogicThe Binary Search only works with sorted lists.

Start by making the smallest index small and the largest index large.

Find the midpoint index with (small + large) / 2

Compare the midpoint value with the search item.

If the value is found you are done.Otherwise re-assign small or large.

If the search item is greater you have a new small,otherwise you have a new large

Repeat the same process.

Continue the process until the search item is found or large becomes less than small.

Page 73: Introduction

Using the Binary Search to Find an Element in an Array Step 1

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]

15 15 23 27 29 32 45 52 60 74 75 89 90 93

Page 74: Introduction

Using the Binary Search to Find an Element in an Array Step 2

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]

15 15 23 27 29 32 45 52 60 74 75 89 90 93

Page 75: Introduction

Using the Binary Search to Find an Element in an Array Step 3

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]

15 15 23 27 29 32 45 52 60 74 75 89 90 93

Page 76: Introduction

Using the Binary Search to Find an Element in an Array Step 4

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]

15 15 23 27 29 32 45 52 60 74 75 89 90 93

Page 77: Introduction

Using the Binary Search to Find an Element in an Array Step 5

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]

15 15 23 27 29 32 45 52 60 74 75 89 90 93

Page 78: Introduction

Using the Binary Search to Find an Element in an Array Step 6

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]

15 15 23 27 29 32 45 52 60 74 75 89 90 93

Page 79: Introduction

Using the Binary Search to Find an Element in an Array Step 7

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]

15 15 23 27 29 32 45 52 60 74 75 89 90 93

Page 80: Introduction

Using the Binary Search to Find an Element in an Array Step 8

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]

15 15 23 27 29 32 45 52 60 74 75 89 90 93