Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Algorithm Definition An algorithm is a step-by-step solution to a problem."— Presentation transcript:

1

2

3 Algorithm Definition An algorithm is a step-by-step solution to a problem.

4 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

5 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.

6

7 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.

8 // Java1301.java // This program reviews generating random numbers with the 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"); }

9

10

11 // Java1302.java // This program introduces the class and the method. The method // generates a random integer in the [0..n-1] range, if n is the integer parameter passed to. 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"); }

12

13

14 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

15 // Java1303.java // This program shows that the 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"); }

16

17

18 Random Integer Algorithm 1.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;

19 // 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 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"); }

20

21 // Java1305.java // A small, but significant change is made in this program. In line-13 the // 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"); }

22

23 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 computer with 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!

24 // MyRandom.java // This class is an example of a user-defined class that // simplifies operating with some Java class, like. 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; }

25 // Java1306.java // This program tests the user-defined 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"); }

26

27 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.

28

29 The List Class Case Study Back 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.

30 // 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(); }

31 class List1 { private int intArray[];// stores array elements private 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(); }

32

33

34 // 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(); }

35 class List2 { private int intArray[ ];// stores array elements private int size; // number of elements in the array private 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(); }

36

37 // Java1309.java List case study #3 // This program uses, 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(); }

38

39

40

41

42 // 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(); }

43

44

45 // 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(); }

46 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.

47

48

49 // 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(); }

50 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.

51

52

53 // 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(); }

54 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.

55

56

57

58 Sorting: Why do we sort? Sorting does not exist in a vacuum. The reason for sorting is to allow more efficient searching.

59 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 – 1 st Pass 4532285738 3245285738 3228455738 3228453857

60 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 – 2 nd Pass 3228453857 2832453857 2832384557

61 28 is not greater than 32; the numbers are left alone. 32 is not greater than 38; the numbers are left alone. The 3 rd pass is complete, and 38 is “known” to be in the correct place. The 4 th pass begins. 28 is not greater than 32; the numbers are left alone. The 4 th pass is complete, and 32 is “known” to be in the correct place. A 5 th 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 – 3 rd & 4 th Pass 2832384557 2832384557 2832384557 2832384557

62 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

63 // 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(); }

64 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 1 st Pass of the Bubble Sort.

65

66 // 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(); }

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

68

69 // Java1316.java List case study #10 // This program introduces the private method that is used by the // 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(); }

70 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.

71

72 Binary Search with a Telephone Book Start 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.

73 Binary Search Logic The 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.

74 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 232729324552607475899093

75 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 232729324552607475899093

76 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 232729324552607475899093

77 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 232729324552607475899093

78 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 232729324552607475899093

79 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 232729324552607475899093

80 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 232729324552607475899093

81 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 232729324552607475899093


Download ppt "Algorithm Definition An algorithm is a step-by-step solution to a problem."

Similar presentations


Ads by Google