vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take...

66
Chapter XIII Algorithms Chapter XIII Topics 13.1 Introduction 13.2 Using Java's Random Class 13.3 The List Case Study 13.4 Improving Input and Output 13.5 The Linear Search 13.6 The Bubble Sort 13.7 Understanding the Binary Search 13.8 Summary Chapter XIII Algorithms Page 525

Transcript of vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take...

Page 1: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Chapter XIII

Algorithms

Chapter XIII Topics

13.1 Introduction

13.2 Using Java's Random Class

13.3 The List Case Study

13.4 Improving Input and Output

13.5 The Linear Search

13.6 The Bubble Sort

13.7 Understanding the Binary Search

13.8 Summary

Chapter XIII Algorithms Page 525

Page 2: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

13.1 Introduction

We need to take a Java break with this chapter. There will be no significant new Java language features introduced. Do keep in mind that you are learning introductory computer science concepts and the language Java is used to teach these concepts. At most high schools BASIC, Pascal, C and C++ were used in computer science before switching to Java. In college you will see a bigger variety in introductory computer science classes. Java is certainly popular, but so are Scheme, Visual BASIC, C++ and other languages, and the choice of the introductory computer science programming language changes quite frequently.

This chapter, however, focuses on an area that does not have many changes: the algorithms used in computer programming. The algorithms presented in this chapter are the same as those presented in corresponding chapters in BASIC, Pascal and C++ books. Sure the language syntax is different, but the essence of the algorithm is unchanged. Do you know what an algorithm is?

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.

Data Structures + Algorithms = Programs

You have done quite a variety of program assignments at this stage and each program required the creation of an algorithm. There were times when you repeated the same types of algorithms for different assignments. The aim of this chapter is to look at a group of practical algorithms that are commonly used in computer science. In particular, we want to look at computer program algorithms that are used to process array information.

This chapter also emphasizes the recurring theme of computer science, not to reinvent the wheel. If practical algorithms have been created for certain situations, use them, store them, and reuse them as some later date. Time is too precious to start from scratch with every program when useful tools have already been created. By the end of this chapter I hope that your programming toolbox will be considerably expanded.

Page 526 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 3: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

13.2 Using Java's Random Class

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. Program Java1301.java, in figure 13.1, generates "true" random numbers. This means that each time you execute the program, there will be a set of numbers that is different and you will not be able to predict the next set of random numbers. The output is shown twice with two different sets of numbers. This is an example of using the random method that was used in earlier program examples using the Expo class.

Figure 13.1

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

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");

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");

}}

Figure 13.1 Output #1

Chapter XIII Algorithms Page 527

Page 4: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Generating numbers in the [10..99] range

51 57 39 64 63 50 69 14 53 39 46 60 82 52 92 17 11 88 44 31 97 17 62 45 17 78 49 80 15 53 54 90 22 11 25 18 23 63 76 89 10 56 35 48 66 80 71 69 88 36 35 66 93 62 35 52 89 85 52 79 73 80 39 81 63 51 93 68 66 10 17 35 29 28 13 50 15 42 65 26 75 14 23 51 65 22 73 89 96 36 21 89 99 48 18 91 48 31 97 82

Generating numbers in the [100..999] range

920 167 612 663 500 796 891 122 791 542 167 391 795 530 253 461 554 309 816 621 960 188 273 755 865 350 140 972 933 755 155 466 737 483 326 618 685 158 758 477 626 389 538 879 879 482 934 412 279 967 348 863 260 541 824 503 735 760 675 667 161 963 505 133 256 351 651 780 618 594 579 713 321 822 735 950 745 134 768 965 214 637 117 212 914 358 857 824 389 873 105 887 917 504 485 672 791 221 170 702

Generating numbers in the [1000..9999] range

2369 7994 7948 8756 3668 9411 6058 5833 4273 7752 3697 4915 6001 4096 7218 1244 8941 5018 6410 5527 8429 7356 6709 6478 2302 4183 1305 4576 4374 7083 7947 8878 2267 1564 3563 5190 3481 3002 7218 2731 8870 5802 5350 5506 8474 4557 6645 6934 2016 8885 7426 7948 1240 9247 3911 5701 9636 8519 1237 9196 7084 9282 5747 4682 1340 4828 3600 2382 2350 4628 6423 1192 3859 4594 5382 7317 8836 2811 9752 2423 8866 5520 3775 2749 9714 6070 4375 2838 1976 7229 2079 5970 7877 6702 2310 5120 2992 7987 7086 7292

Figure 13.1 Output #2Generating numbers in the [10..99] range

22 28 85 68 28 23 94 92 81 12 71 62 65 64 97 84 90 46 94 59 99 78 51 29 36 80 30 83 34 17 48 30 23 12 85 95 26 40 55 82 29 26 94 75 37 33 83 36 33 61 94 93 98 24 67 18 30 57 16 85 70 34 46 26 15 51 47 96 18 17 22 40 55 71 91 40 38 77 36 33 36 27 20 41 47 56 47 15 43 68 81 12 57 84 44 80 25 87 48 27

Generating numbers in the [100..999] range

514 312 942 786 314 749 456 103 133 580 900 303 449 544 491 617 955 762 211 411 495 678 503 929 731 721 335 585 308 805 959 424 161 561 794 912 323 490 694 111 985 248 730 970 341 615 946 250 906 823 475 270 793 322 330 615 949 788 103 884 126 738 778 957 575 358 292 470 204 841 640 373 206 416 198 176 348 761 808 782 423 312 816 790 428 126 505 173 852 695 904 347 383 902 966 189 143 669 663 334

Generating numbers in the [1000..9999] range

8617 9736 3865 6343 5105 4045 7284 8446 8691 9760 6270 5445 6909 7625 3965 3600 2909 2765 4978 4447 1311 6979 1932 7835 9257 5525 1560 6799 5205 6516 5736 5425 8291 5293 8909 8082 9225 5560 4893 2260 3759 7657 9873 7787 9759 2053 6771 4392 8756 7042 2844 3394 7665 9690 5485 5829 2053 1224 1726 5458 5915 8489 2866 2906 9441 2528 3974 6669 4668 3082 1786 9823 8210 9586 5602 2070 3504 5229 2408 7171 3131 4805 9359 6920 4802 2339 7142 9549 3550 8950 1498 2882 5515 3016 6383 8570 2458 1459 9794 6512

Page 528 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 5: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Introducing Java's Random Class

The Expo class random number generating is simple, but it has its limitations. Furthermore, let's face it, you are at the end of this course and you can certainly handle some greater complexity.

All the methods in the Expo class are class methods, which is by design. It is easier to call class methods since you do not have to start by instantiating an object first. Java's Random class requires that an object is constructed and program Java1302.java, in figure 13.2 generates three sets of numbers in three different ranges. Note that after the object rand is created, method nextInt generates a random integer. The parameter of nextInt is an upper limit. A call, like nextInt(100) will generate integers in the [0..99] or more generally speaking you can say that a call to nextInt(n) generates numbers in the [0..n-1] range.

Figure 13.2// 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");

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");

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");

}}

Chapter XIII Algorithms Page 529

Page 6: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Figure 13.2 Output #1Generating numbers in the [0..99] range

52 21 15 46 23 1 89 25 53 53 38 63 92 74 8 72 6 53 26 90 69 15 74 26 15 44 46 35 63 45 70 75 35 35 10 30 85 12 85 98 33 21 88 69 81 90 71 10 84 54 46 43 76 14 9 91 47 14 26 44 82 18 59 19 77 28 61 33 51 72 10 19 77 76 72 86 26 10 55 30 91 59 1 44 2 11 2 41 93 59 54 22 23 75 95 15 82 58 68 97

Generating numbers in the [0..999] range

97 131 436 57 62 210 686 598 521 768 953 670 107 299 739 293 21 818 546 331 597 442 610 261 475 99 468 562 707 122 17 656 203 675 532 746 427 730 461 561 388 863 369 173 17 20 503 693 962 283 30 602 264 505 833 509 451 74 45 872 878 879 369 304 836 427 156 293 724 21 277 803 504 274 883 808 52 571 837 194 729 807 652 940 353 797 92 437 132 872 57 822 953 270 391 614 753 39 89 540

Generating numbers in the [0..9999] range

390 791 4971 2783 1889 8664 4028 4197 3904 9847 8410 4263 1542 2392 1001 7389 5484 6921 3863 1739 1573 5929 558 7463 5840 4275 4141 7126 8454 9067 9152 771 1827 8323 3211 7963 6002 2154 5814 3847 5297 434 3058 103 4308 5516 650 664 1909 7826 1444 1090 4201 8833 2855 272 1389 9714 807 9868 4559 435 7355 5622 1705 2822 9744 2337 4089 3317 8742 6587 4812 5761 40 2391 3464 6230 6569 7193 9401 7932 6586 5997 1187 3469 9224 8532 8486 2046 3058 5212 4736 5627 2872 6826 9580 9364 4783 9047

Figure 13.2 Output #2Generating numbers in the [0..99] range

89 93 30 21 18 62 73 41 47 7 74 5 77 22 83 14 12 99 76 61 17 26 97 79 47 94 50 27 58 45 16 88 89 56 70 98 80 51 39 96 45 54 58 32 72 14 14 12 62 95 81 22 18 7 8 35 99 72 20 56 47 60 35 21 30 66 38 87 20 48 31 54 60 4 36 56 56 20 6 25 86 95 77 80 6 98 80 67 67 75 74 72 40 45 56 16 39 77 50 4

Generating numbers in the [0..999] range

384 222 742 726 601 989 654 977 643 263 143 6 589 391 842 29 24 419 0 940 466 967 586 495 493 70 22 468 484 39 325 689 286 488 770 949 27 249 469 136 75 679 53 647 798 219 61 376 694 815 21 198 184 748 825 161 194 283 366 918 62 734 377 407 973 842 778 430 903 684 645 739 782 181 505 591 874 435 785 981 975 117 57 948 971 130 394 147 867 79 750 946 117 731 200 680 752 553 266 247

Generating numbers in the [0..9999] range

1128 1122 5290 2496 238 4324 9958 3267 5828 2290 4836 7872 8758 5705 7862 4691 6412 6589 3563 9312 5004 38 1353 2067 5340 6122 3302 8946 7621 4344 5318 7681 5475 3102 8143 9266 4601 8424 5896 9863 529 1910 9760 9221 6209 3432 9131 6919 9721 2345 2966 4572 5657 7925 1132 9822 2448 7943 7249 9408 8015 4084 5115 3571 1083 7774 545 3925 4946 4086 4076 8806 1989 6001 6842 3816 9843 4965 881 771 7174 5617 1056 5155 374 6103 5985 4143 6684 2534 1227 9366 2802 360 3844 551 725 196 7524 2701

Page 530 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 7: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

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 integer in [0..99] rangeint n2 = rand.nextInt(500]; // random integer in [0..499] rangeint n3 = rand.nextInt(n); // random integer in [0..n-1] range

Random numbers that are always in a range starting with 0 are not very practical. How does the Random class handle other ranges? Program Java1303.java, in figure 13.3, shows various examples. You will note that the secret is to add an integer value to the result of the nextInt method call. In each case the integer value added will be the minimum number in the requested range.

Figure 13.3

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

Chapter XIII Algorithms Page 531

Page 8: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

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");

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");

}}

Figure 13.3 Output #1

Generating numbers in the [10..99] range

60 47 24 48 70 70 84 35 89 63 67 51 93 60 34 31 90 21 39 50 72 90 31 42 10 44 37 54 25 32 36 31 18 94 89 93 20 42 63 11 83 16 66 81 18 31 64 60 89 21 57 48 49 33 46 38 89 93 39 39 42 52 43 45 99 27 65 38 77 25 47 79 15 87 76 54 88 28 64 35 97 96 87 14 44 65 80 22 37 14 98 33 26 68 77 13 47 40 61 23

Generating numbers in the [100..999] range

287 591 746 534 264 224 604 123 809 355 746 556 410 637 936 807 267 651 227 700 672 300 567 620 141 750 318 890 975 598 557 282 170 938 478 165 559 490 373 554 379 174 176 572 535 116 207 377 264 317 954 175 526 947 518 893 812 163 994 589 259 600 414 237 609 224 519 596 774 190 722 455 702 754 920 878 541 506 336 746 274 273 627 784 507 722 644 868 671 451 299 471 467 767 924 874 556 999 773 760

Generating numbers in the [1000..9999] range

7670 4421 3762 1968 1745 6283 3850 2645 8260 9740 4431 5171 5170 2304 9459 4344 8454 2482 7165 4011 8916 3886 3163 6688 9451 2029 6162 4432 5078 7782 9616 4989 3457 2035 7763 9159 8697 6629 3218 1614 2004 6525 9473 1700 5752 6737 6906 8790 8808 3694 7150 5671 2824 5456 7924 4641 6689 6403 3120 3801 9528 9485 3101 7973 2785 1339 1853 5581 9162 4053 6204 9212 5066 7878 7445 8825 7904 5171 6196 3230 3159 9696 7323 5940 6735 4249 8040 2033 1567 7172 4092 3544 6206 7521 5310 6395 7802 9602 2957 2262

Page 532 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 9: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Figure 13.3 Output #2

Generating numbers in the [10..99] range

77 87 61 53 60 47 67 76 36 69 44 11 20 83 63 25 96 41 19 92 15 96 59 70 96 32 36 51 35 70 38 17 26 71 16 30 83 96 86 70 29 41 43 87 95 36 23 12 97 95 63 74 24 44 80 61 57 78 19 30 40 74 82 48 54 30 78 29 19 23 10 17 81 94 81 14 15 88 29 21 29 13 47 20 84 35 98 76 15 89 76 56 87 84 89 95 85 15 42 62

Generating numbers in the [100..999] range

765 102 332 852 860 528 649 511 590 321 282 845 365 510 749 997 546 980 140 526 773 539 747 212 479 259 350 125 640 254 363 180 873 352 219 118 705 704 417 551 372 572 937 414 221 156 350 513 124 984 715 900 345 208 533 819 564 198 246 803 299 860 807 522 426 415 547 721 416 808 251 528 601 805 514 323 644 551 258 976 667 299 782 279 261 424 119 519 894 570 582 636 907 437 963 279 782 432 724 963

Generating numbers in the [1000..9999] range

8763 2563 3506 3196 6801 1192 5701 2069 6806 8327 1684 7082 7825 6582 8991 8165 1258 2321 8581 2351 9337 1618 2610 1572 9309 1005 5717 7936 9608 6890 4903 6820 1631 6407 7183 7777 4008 9521 3299 6272 8524 1376 8658 1155 2996 1525 4948 3876 2055 9800 7666 2328 7657 5050 5226 6862 8272 1315 6147 7730 8080 9553 9175 9577 7534 1007 8174 7857 1922 4661 3887 7087 9149 3106 1722 6444 3690 9130 1384 2484 1369 2565 5812 2164 5718 3503 1843 7832 7025 6501 5534 9070 6262 7378 6465 1378 9860 5142 1411 4567

Program Java1304.java, in Figure 13.4, shows that there is an algorithm to manipulate random numbers. This program also allows the user to enter the minimum and maximum values from the keyboard.

Chapter XIII Algorithms Page 533

Page 10: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

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;

Figure 13.4

// 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 < 200; k++){

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

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

}}

Page 534 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 11: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Figure 13.4 Output #1

Enter minimum random integer ===>> 1000Enter maximum random integer ===>> 9999

Generating numbers in the [1000..9999] range

4452 3748 3333 2508 2103 4338 8134 9776 2126 3841 5959 4587 2832 5122 4462 6037 7546 6696 5676 1065 8111 4157 4763 4692 3943 5408 4339 4326 3751 3539 7608 7405 8644 2915 6172 9216 1645 5018 3285 5641 5397 1030 1986 4068 2530 8340 9783 7580 1253 4311 7258 8349 6526 2578 4754 3500 9083 7214 7964 9298 8892 5708 9561 4975 5631 2028 6871 2772 6155 7478 6369 7865 3987 9806 2190 9725 9593 5549 1252 9883 6612 1394 8846 2305 6767 9455 7537 6236 5231 1200 8375 4888 1113 2926 4110 7404 1646 9394 1793 7746

Figure 13.4 Output #2

Enter minimum random integer ===>> 1000Enter maximum random integer ===>> 9999

Generating numbers in the [1000..9999] range

5578 9153 4065 2592 9675 3797 2108 6671 3074 5453 2864 1481 9993 3131 6091 8815 5991 3881 5885 8478 7432 4763 9798 2951 7378 2585 5316 2551 8042 5629 3890 5585 5402 7147 5032 6162 9847 3125 9059 4181 4090 1990 1258 7444 2819 2454 2068 7520 5997 5364 4969 8560 3627 6683 6123 4197 4517 7859 2728 8590 3214 1616 1767 7103 6924 3976 1901 6836 9501 5269 6603 4588 5291 2778 3542 8505 7316 6194 9738 1051 5041 2637 4475 9820 5737 6380 1266 2334 4817 5219 1009 2657 5010 1430 7619 2137 6423 9124 1971 9123

Finally, we come to the point of this section, which is the ability to generate random numbers that are not random. Have the Schrams finally lost it or did that happen some time ago? Have patience, it will make sense. Program Java1305.java, in figure 13.5, makes a very significant change from the previous program. A different Random constructor is used with a parameter. You will note in the three output samples that the first output looks random as before, but the second and third output are identical to the first one.

Figure 13.5

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

Chapter XIII Algorithms Page 535

Page 12: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

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");

}}

Figure 13.5, Output #1

Enter minimum random integer ===>> 1000Enter maximum random integer ===>> 9999

Generating numbers in the [1000..9999] range

6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Figure 13.5, Output #2

Enter minimum random integer ===>> 1000Enter maximum random integer ===>> 9999

Generating numbers in the [1000..9999] range

6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Page 536 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 13: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Figure 13.5, Output #3

Enter minimum random integer ===>> 1000Enter maximum random integer ===>> 9999

Generating numbers in the [1000..9999] range

6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Now we come to a logical question. Why would anybody want to have random numbers that seem to be predictable? It actually occurs in many situations. Imagine that multiple teams compete in some randomly generated card game or any other video game for that matter. To eliminate the element of luck by drawing good cards or bad cards, everybody draws the same cards. For the players the cards will seem random. The lack of randomness will only appear if the same program is run a second or third time.

Another example occurs when students in a computer science course need to write a challenging lab assignment. They must write a program that manages to find a path from a randomly generated maze. The instructor may want to test this program with the same maze for every student to get a proper comparison.

The final stage in our random quest is a program enhancement. You are now convinced that controlling random numbers is a worthwhile project. You have decided, or your instructor has decided, to create a class to handle random numbers.

This class is called MyRandom. It will have the simplicity of the Expo class since you can enter minimum and maximum values, but it will also let you select true random values or pseudo random values. MyRandom.java, in figure 13.6 shows the user-defined class and Java1306.java, in figure 13.7, is used to test the MyRandom class.

Any MyRandom object constructed without seed parameter will be truly random and an object constructed with a seed will be pseudo random.

Chapter XIII Algorithms Page 537

Page 14: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Figure 13.6

// 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;

}}

Figure 13.7

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

}}

}

Page 538 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 15: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Figure 13.7, Output #1

Enter minimum random integer ===>> 1000Enter maximum random integer ===>> 9999

Generating true random numbers in the [1000..9999] range

7171 6201 6871 8401 7559 2398 1801 1980 8933 3813 5155 5529 2985 7020 4266 4878 6816 3904 5913 4663 1764 9507 8216 8497 9594 8641 1136 2792 7203 9352 8946 5557 4734 6073 1047 8887 7103 8215 8834 6020 7640 1187 6178 2013 2117 7481 7868 5644 6222 5675 3245 6050 5350 6785 2004 7233 4993 1025 2014 3755 9202 7816 7363 6446 5337 7813 7158 6964 7124 5990 3027 7243 7485 4994 7032 8061 3001 6242 4454 9517 2728 1116 1801 2151 1000 1174 8762 3746 3052 2932 8870 9014 9834 4022 5487 8220 9466 1784 1560 1662

Generating pseudo random numbers in the [1000..9999] range

5628 3633 8133 6220 6210 1393 7529 6449 4297 7037 4760 4038 4047 4286 8889 6364 5450 1012 8897 1927 4974 7559 1907 9946 3178 1363 8072 1696 9989 8806 8218 6044 5054 3226 9050 2054 9673 9618 9553 5643 1741 6690 2876 8623 2090 9167 4944 2410 9456 5928 2997 6900 5706 8896 2240 3934 7218 6553 4120 1879 2262 6943 9129 8303 9256 5430 8103 8628 7195 6720 4466 3478 7089 5759 2584 2697 9073 3068 9057 7199 6414 4873 1676 1951 7875 4793 5070 7382 8523 9578 2954 6328 5445 4076 4668 8691 9964 3161 2384 7057

Figure 13.7, Output #2

Enter minimum random integer ===>> 1000Enter maximum random integer ===>> 9999

Generating true random numbers in the [1000..9999] range

2285 9937 5379 1850 6804 5749 9271 8669 8089 6740 9824 7822 7789 5196 2856 1667 3707 4950 8341 8841 7884 3561 9538 5588 5399 6243 7201 4433 5752 7565 7021 8755 4849 3314 8499 9058 2375 3779 6520 4293 7003 5090 5661 8519 3321 5529 8288 5469 6837 5927 1221 7851 1097 8806 2137 8582 9763 1188 4415 4753 2723 9003 3411 6791 6811 3431 2211 6169 4623 2036 6574 2221 5395 2394 9236 5452 2652 6062 4165 6718 4646 7798 3215 3532 7813 5920 4887 4170 4688 3255 3968 9719 6503 4443 1025 2562 5973 2125 9680 6099

Generating pseudo random numbers in the [1000..9999] range

5628 3633 8133 6220 6210 1393 7529 6449 4297 7037 4760 4038 4047 4286 8889 6364 5450 1012 8897 1927 4974 7559 1907 9946 3178 1363 8072 1696 9989 8806 8218 6044 5054 3226 9050 2054 9673 9618 9553 5643 1741 6690 2876 8623 2090 9167 4944 2410 9456 5928 2997 6900 5706 8896 2240 3934 7218 6553 4120 1879 2262 6943 9129 8303 9256 5430 8103 8628 7195 6720 4466 3478 7089 5759 2584 2697 9073 3068 9057 7199 6414 4873 1676 1951 7875 4793 5070 7382 8523 9578 2954 6328 5445 4076 4668 8691 9964 3161 2384 7057

Chapter XIII Algorithms Page 539

Page 16: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Truly Random and 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.

13.3 The List Case Study

Back in Chapter XI, 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. This first stage is shown in program Java1307.java, shown in figure 13.8. The main method of the program tests the List class.

Page 540 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 17: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Each stage of the case study has a number. This class has four methods right now, two constructors, an assign method and a display method.

The first constructor has one parameter to indicate the number of array elements. The second constructor has two parameters. The first parameter is for the array size, the second parameter indicates the initial value for each array element.

The assign method assigns new values to each array element, using random values in the [1000..9999] range, using our brand new MyRandom class. The display method shows the value for each element of a List object, called array1 and array2 in this program.

This program and a few later programs will include the entire List class with the program. As the case study advances and grows with each additional method, only the main method and the latest addition of the List class will be shown by itself. Some methods, which are not used in future program examples, will be deleted from the List class. This approach will create greater program clarity and allows more focus on the newest methods.

Figure 13.8

// 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.assignRandom();array2.display();System.out.println();

}}

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];

}

Chapter XIII Algorithms Page 541

Page 18: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

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 assignRandom (){

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();

}}

Figure 13.8 Continued

CONSTRUCTING NEW LIST OBJECT WITH DEFAULT VALUES

DISPLAYING ARRAY ELEMENTS0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

CONSTRUCTING NEW LIST OBJECT WITH SPECIFIED VALUES

DISPLAYING ARRAY ELEMENTS999 999 999 999 999 999 999 999 999 999 999 999 999 999 999

ASSIGNING RANDOM VALUES TO LIST OBJECT

DISPLAYING ARRAY ELEMENTS6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012

Page 542 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 19: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

List Case Study #2, Adding a Third Constructor

The assign method provides a set of random values for a List object. These values are always in the [1000..9999] range. Our next step is to create a third constructor that can control the kind of random values that will be assigned to a new List object.

Three parameters are necessary for this new constructor. The first parameter specifies the size of the new List object. The second parameter indicates the smallest possible random integer value. The third parameter passes the value of the largest upper bound value of the random integer range. Program Java1308.java, in figure 13.9, demonstrates the use of this new constructor. Four objects are instantiated with four different random integer ranges. The range of the integers is displayed by the constructor method.

Figure 13.9

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

}}

class List2{

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

Chapter XIII Algorithms Page 543

Page 20: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

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

}

Figure 13.9 Continued

CONSTRUCTING LIST WITH VALUES in [0..100] range

DISPLAYING ARRAY ELEMENTS16 9 34 39 89 74 78 82 44 69 52 95 68 2 68

CONSTRUCTING LIST WITH VALUES in [100..999] range

DISPLAYING ARRAY ELEMENTS851 680 241 928 455 284 575 802 701 889 717 142 890 206 312

CONSTRUCTING LIST WITH VALUES in [0..1] range

DISPLAYING ARRAY ELEMENTS0 1 1 1 1 0 0 0 0 0 0 1 0 1 1

CONSTRUCTING LIST WITH VALUES in [500..505] range

DISPLAYING ARRAY ELEMENTS501 504 503 500 501 504 501 500 501 503 505 500 504 504 502

Page 544 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 21: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

13.4 Improving Input and Output

Before we go too much further with some new algorithms, it is time to make the List class more user-friendly in the input/output department. Output of any sizeable list will fly by on the monitor without allowing proper viewing of the intermediate values. Input right now does not exist. The size of the List objects and the range of the values are hard coded in the programs. This is not a satisfactory arrangement.

The first issue of too much output is handled by program Java1309.java, in figure 13.10. This program adds the pause method, of the Expo class, to the List class. We are not looking at a breaking news method, but a small, practical method, which stops program execution until the <Enter> key is pressed. The programmer can select where to call this method to control program output. In the case of the current program example, pause is called after the display of each list. The result is that the elements of each separate list can be viewed before displaying the next list.

Figure 13.10

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

}}

Chapter XIII Algorithms Page 545

Page 22: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

class List3{

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

public List3(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();

}}

Figure 13.10 Continued

CONSTRUCTING LIST WITH VALUES in [100..200] range

DISPLAYING ARRAY ELEMENTS116 109 134 139 189 174 178 182 144 169 152 195 168 102 168 158 191 105 170 169 147 196 109 112 117 188 187 186 148 165 180 111 147 180 196 112 181 177 171 193 175 120 150 150 153 195 101 116 197 107 141 166 172 135 197 154 195 155 116 113

Press the <enter> key to continue...

CONSTRUCTING LIST WITH VALUES in [100..999] range

DISPLAYING ARRAY ELEMENTS851 680 241 928 455 284 575 802 701 889 717 142 890 206 312 584 687 803 432 775 201 851 992 116 228 481 525 843 171 739 229 297 301 425 903 855

Page 546 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 23: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

852 931 710 608 496 182 799 558 318 980 712 791 750 628 274 944 154 608 180 199 258 955 794 697 694 487 353 218 783 599 970 473 490 719 876 921 218 656 488 226 649 392 552 575 103 500 832 664 175 644 709 555 198 116 587 539 653 667 551 541 515 966 274 377

Press the <enter> key to continue...

CONSTRUCTING LIST WITH VALUES in [10..19] range

DISPLAYING ARRAY ELEMENTS11 10 11 18 15 14 15 12 11 19 17 12 10 16 12 14 17 13 12 15 11 11 12 16 18 11 15 13 11 19 19 17 11 15 13 15 12 11 10 18 16 12 19 18 18 10 12 11 10 18 14 14 14 18 10 19 18 15 14 17 14 17 13 18 13 19 10 13 10 19 16 11 18 16 18 16 19 12 12 15 13 10 12 14 15 14 19 15 18 16 17 19 13 17 11 11 15 16 14 17 10 14 15 11 16 19 16 19 10 14 14 15 12 16 16 10 16 11 14 13 14 15 12 15 13 16 15 13 15 17 18 14 19 10 13 11 16 19 19 19 18 16 13 10 12 12 17 18 18 11 16 18 17 17 18 16 18 15 14 14 15 12 16 16 17 16 14 19 17 11 18 10 18 15 17 11 17 10 14 15 18 13 17 13 19 10 13 12 10 18 12 11 16 19 10 18 19 11 18 10

Press the <enter> key to continue...

CONSTRUCTING LIST WITH VALUES in [500..505] range

DISPLAYING ARRAY ELEMENTS501 504 503 500 501 504 501 500 501 503 505 500 504 504 502 504 505 501 502 503 505 501 504 504 502 503 505 505 505 503 503 505 503 501 505 505 502 503 504 504

Press the <enter> key to continue...

Chapter XIII Algorithms Page 547

Page 24: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

List Case Study #4, Keyboard Input

This stage is quite significant. The program user now can take control of the program execution process. The three List constructor parameters of listSize, listMin and listMax will be prompted and entered at the keyboard. The input process will be handled by the main method and the input values will then be used to construct the requested List objects. Program Java1310.java, in figure 13.11, executes the program and then prompts for user input.

Figure 13.11

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

}}

class List4{

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

public List4(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);}

Page 548 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 25: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

public void display(){

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

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

}}

Figure 13.11 Continued

Enter list size ===>> 100Enter minimum value ===>> 1000Enter maximum value ===>> 9999

CONSTRUCTING LIST WITH VALUES in [1000..9999] range

DISPLAYING ARRAY ELEMENTS6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Press the <enter> key to continue...

Chapter XIII Algorithms Page 549

Page 26: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

13.5 The Linear Search

Now let us look at what happens in the real world. In a moment of weakness your mother or father gives you a credit card to do shopping at the local mall. You are excited and tightly clutch the piece of plastic in your hands. At each one of the stores you hand the credit card for payment. Is your new purchase now yours? No it is not. First you have to wait while the store clerk determines if your credit card can handle the purchase. Is the card valid? Does the card have sufficient credit left in its balance? These questions can only be answered by finding the information record associated with your parents’ credit card. In other words, a computer needs to perform a search to find the proper credit card record.

The credit card is but one example. In an auto parts store, a clerk punches in some part number and the computer searches to see if the part exists in inventory. And now in the modern Internet world searching takes on a new meaning when special programs, called search engines, look for requested topics on the ever- expanding World Wide Web. In other words, searching is a major big deal and in this chapter we start to explore various ways that you can search for requested elements in an array.

There is no simpler search than the Inefficient Linear Search. In this search you start at the beginning of a list and traverse to the end, comparing every element along the way. A Boolean variable is set to true if a match is found. The linearSearch method is shown first, by itself in figure 13.12. Then program Java1311.java, in figure 13.13, demonstrates this first searching approach. In just a moment we will explain why this search is called inefficient. This algorithm is called linear or sometimes sequential because it starts at one end and goes in a linear or sequential progression to the end. There are two program outputs, one for an existing number and a second output for a non-existing number.

Figure 13.12

public boolean linearSearch(int sn) { boolean found = false; for (int k = 0; k < size; k++) if (intArray[k] == sn) found = true; return found; }

Page 550 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 27: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Figure 13.13

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

}}

class List5{

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

public List5(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();

Chapter XIII Algorithms Page 551

Page 28: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

}

public boolean linearSearch(int sn){

boolean found = false;for (int k = 0; k < size; k++)

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

return found;}

}

Figure 13.13, Output #1

Enter list size ===>> 100Enter minimum value ===>> 1000Enter maximum value ===>> 9999

CONSTRUCTING LIST WITH VALUES in [1000..9999] range

DISPLAYING ARRAY ELEMENTS6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Press the <enter> key to continue...

Enter search number ===>> 70107010 is in the list

Figure 13.13, Output #2

Enter list size ===>> 100Enter minimum value ===>> 1000Enter maximum value ===>> 9999

CONSTRUCTING LIST WITH VALUES in [1000..9999] range

DISPLAYING ARRAY ELEMENTS6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781

Page 552 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 29: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Press the <enter> key to continue...

Enter search number ===>> 11111111 is not in the list

Did you understand why this Linear Search algorithm is called inefficient? What happens when the search number is the very first number in the list? The loop still continues and compares every element in the array until the end. This is flat silly. Imagine that you are at a car repair shop and after your file is found, the clerk continues to check every file. The next search algorithm is a more civilized Linear Search and uses a Boolean variable both to signal that the requested element is found as well as a loop condition to terminate the search. Figure 13.9 compares the previous Linear Search with the improved algorithm and program.

Figure 13.14Inefficient Linear Search Efficient Linear Search

public boolean linearSearch(int SN) { boolean found = false; for (int k = 0; k < Size; k++) if (intArray[k] == sn) found = true; return found; }

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

Chapter XIII Algorithms Page 553

Page 30: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Java1312.java, in figure 13.15, demonstrates the altered algorithm. Do not expect to see any difference in execution speed. With today's computers, you will need to search a rather substantial list size to make any measurable comparisons.

Figure 13.15

// Java1312.java// List case study #6// The inefficient <linearSearch> is improved 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();

}}

class List6{

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

public List6(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);}

Page 554 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 31: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

public void display(){

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

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

}

public boolean linearSearch(int sn){

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

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

elsek++;

}return found;

}}

Figure 13.15, Output #1

Enter list size ===>> 100Enter minimum value ===>> 1000Enter maximum value ===>> 9999

CONSTRUCTING LIST WITH VALUES in [1000..9999] range

DISPLAYING ARRAY ELEMENTS6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Press the <enter> key to continue...

Enter search number ===>> 70107010 is in the list

Chapter XIII Algorithms Page 555

Page 32: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Figure 13.15, Output #2

Enter list size ===>> 100Enter minimum value ===>> 1000Enter maximum value ===>> 9999

CONSTRUCTING LIST WITH VALUES in [1000..9999] range

DISPLAYING ARRAY ELEMENTS6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Press the <enter> key to continue...

Enter search number ===>> 11111111 is not in the list

You might be satisfied with the improved Linear Search, but we are not. The actual Java implementation of the search is really not very practical. You are told that some requested number exists or it does not exist. In real life searches normally provide information about the location of a successful search. Imagine a very large warehouse with stocked inventory. Your trusty computer has told you that Inventory part #548321-A is stocked. Well you are so pleased since there are only 200,000 parts stored and finding 548321-A should be a breeze. The next stage, program Java1313.java, in figure 13.16, of the case study uses the efficient Linear Search algorithm and returns the index value of the array element if the item is found. An index value of -1 is returned if the search item is not in the list.

Figure 13.16

// Java1313.java// List case study #7// This program makes the <linearSearch> method more practical// by returning the index of the <searchNumber> or -1 if not found.

public class Java1313{

public static void main(String args[])

Page 556 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 33: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

{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();

}}

class List7{

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

public List7(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();

}

Chapter XIII Algorithms Page 557

Page 34: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

public int linearSearch(int sn){

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

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

elsek++;

}if (found)

return k;else

return -1;}

}

Figure 13.16, Output #1

Enter list size ===>> 100Enter minimum value ===>> 1000Enter maximum value ===>> 9999

CONSTRUCTING LIST WITH VALUES in [1000..9999] range

DISPLAYING ARRAY ELEMENTS6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Press the <enter> key to continue...

Enter search number ===>> 70107010 is found at index 38

Page 558 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 35: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Figure 13.16, Output #2

Enter list size ===>> 100Enter minimum value ===>> 1000Enter maximum value ===>> 9999

CONSTRUCTING LIST WITH VALUES in [1000..9999] range

DISPLAYING ARRAY ELEMENTS6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Press the <enter> key to continue...

Enter search number ===>> 11111111 is not in the list

13.6 The Bubble SortWe will return to more searching in a later section. Right now we need to leave searching behind to learn some other algorithms. Any additional improvements on searching algorithms will require that the data are sorted. Do you believe that anybody is really interested in sorting? Do not get confused, sorting is extremely important, but only because we desire searching. File cabinets have files neatly alphabetized or organized according to account numbers or some other order.

These files are organized according to a sorting scheme for the purpose of finding the files easily. It is the same with library books that are organized in categories and sorted according to some special library number.

Chapter XIII Algorithms Page 559

Page 36: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Why Do We Sort?

Sorting does not exist in a vacuum.

The reason for sorting is to allow more efficient searching.

The first sort in this chapter is the Bubble Sort. This humble sort gets a lot of bad press. The poor Bubble Sort is banned from many textbooks and not allowed to be uttered in certain computer science environments. Why? It is by far the most inefficient sort in a large arsenal of sorts. However, it also happens to be the easiest sort to explain to students first introduced to sorting algorithms. There is a secondary motivation. This chapter does not have as its primary motivation to study algorithmic efficiency. You are only getting started. This does not prevent a gentle introduction, and a small taste, of certain efficiency considerations. Starting with an inefficient algorithm like the Bubble Sort helps to point out certain efficiency problems and how they can be improved. The Bubble Sort gets its name because data bubbles to the top, one item at a time.

Consider the following small array of five numbers, shown in Figure 13.17. It will be used to demonstrate the logic of the Bubble Sort step-by-step. At every stage, adjacent numbers are compared, and if two adjacent numbers are not in the correct place, they are swapped. Each pass through the number list places the largest number at the top. It has bubbled to the surface. The illustrations show how numbers will be sorted from smallest to largest. The smallest number will end up in the left-most array location, and the largest number will end up in the right-most location.

Figure 13.17

45 32 28 57 38

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

32 28 45 57 38

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

Page 560 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 37: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Figure 13.17 Continued

32 28 45 57 38

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

32 28 45 38 57

One pass is now complete. The largest number, 57, is in the correct place.A second pass will start from the beginning with the same logic.32 is greater than 28; the two numbers need to be swapped.

28 32 45 38 57

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

28 32 38 45 57

We can see that the list is now sorted. Our current algorithm does not realize this.It is not necessary to compare 45 and 57. The second pass is complete, and 45 is in the correct place.The third pass will start.28 is not greater than 32; the numbers are left alone.32 is not greater than 38; the numbers are left alone.

28 32 38 45 57

The third pass is complete, and 38 is “known” to be in the correct place.The fourth - and final - pass will start.28 is not greater than 32; the numbers are left alone.

28 32 38 45 57

The fourth pass is complete, and 32 is “known” to be in the correct place.A fifth 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.

Chapter XIII Algorithms Page 561

Page 38: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Bubble Sort Algorithm

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

Continue this process until the largest element is inthe 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-lastelement of the array.

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

You are armed with the logic of a Bubble Sort routine. Now how do you translate such an algorithm into Java program code? How about in gentle stages? Program Java1314.java, in figure 13.18, adds the partialSort method. It is an incomplete Bubble Sort that only places one element, the largest, in the correct location. If we can understand this step, then it will be easier to see how the entire sort works.

Figure 13.18

// 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 562 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 39: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

class List8{

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

public List8(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();

}

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;

}}

}

Figure 13.18 Continued

Enter list size ===>> 100Enter minimum value ===>> 1000Enter maximum value ===>> 9999

CONSTRUCTING LIST WITH VALUES in [1000..9999] range

DISPLAYING ARRAY ELEMENTS6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781

Chapter XIII Algorithms Page 563

Page 40: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Press the <enter> key to continue...

DISPLAYING ARRAY ELEMENTS6080 6251 1828 4055 2084 2375 9241 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9802 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677 9903

The partialSort method shows the required code for placing one array element in the correct place. It represents one so-called comparison pass. How many of these passes need to be made? You are correct. There are n-1 comparison passes, with n equal to the number of elements in the list. If we take the previous PartialSort method and package that inside another loop structure, which executes n-1 times, we might just be in business. Program Java1315.java, in Figure 13.19, demonstrates the completed bubbleSort method.

Figure 13.19

// Java1315.java// List case study #9// This program sorts in ascending order using the Bubble Sort.// This version of the BubbleSort is very inefficient.// It compares numbers that are already in 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();

Page 564 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 41: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

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

}}

class List9{

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

public List9(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();

}

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;

}}

}

Chapter XIII Algorithms Page 565

Page 42: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Figure 13.19 Continued

Enter list size ===>> 100Enter minimum value ===>> 1000Enter maximum value ===>> 9999

CONSTRUCTING LIST WITH VALUES in [1000..9999] range

DISPLAYING ARRAY ELEMENTS6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Press the <enter> key to continue...

DISPLAYING ARRAY ELEMENTS1003 1054 1158 1174 1396 1425 1439 1499 1508 1544 1691 1828 1831 1942 2084 2375 2384 2497 2501 2517 2519 2583 2594 2792 2871 2918 3012 3188 3364 3367 3409 3412 3439 3555 3644 3655 3801 3806 3826 3992 4055 4087 4141 4294 4350 4580 4729 4774 4990 5055 5108 5303 5351 5389 5390 5466 5582 5599 5825 5900 6056 6080 6175 6251 6370 6677 6773 6781 6875 6953 7010 7099 7316 7380 7398 7428 7501 7553 7715 7758 7849 8076 8121 8275 8318 8397 8532 8687 8728 8787 8943 8952 9116 9241 9318 9551 9552 9802 9832 9903

At the start of the Bubble Sort section we mentioned that it is good to start with an inefficient sort. This helps to appreciate efficiency and thinking about efficiency as improvements are made. So can you think of any improvements? We bet there are some clever students who realize that each comparison pass makes the same number of comparisons. Now, that is not very clever, because after each pass there is another number in the correct location. Some mechanism needs to be used to reduce comparisons for each pass.

There is also the issue of readability. Readability is an odd type of efficiency. When a program is made more readable it does not execute faster, but it debugs and updates faster. The ability to fix or update a program is a different, but also very important efficiency consideration. Our bubbleSort method includes some lines of code that swap the adjacent list items. We can gain readability by creating a swap method. Furthermore, we should make this method private, because it is only used within the List class by the member bubbleSort method.

Page 566 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 43: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Program Java1316.ava, in Figure 13.20, addresses both improvements. Do you understand why the number of comparison passes are reduced with each iteration?

Figure 13.20

// Java1316.java// List case study #10// This program introduces the private <swap> method that is used by the// <bubbleSort> and other methods.// The improved <bubbleSort> also improves the algorithm by// reducing the number of comparisons 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();

}}

class List10{

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

public List10(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);}

Chapter XIII Algorithms Page 567

Page 44: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

public void display(){

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

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

}

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);

}

}

Figure 13.20 ContinuedEnter list size ===>> 100Enter minimum value ===>> 1000Enter maximum value ===>> 9999

CONSTRUCTING LIST WITH VALUES in [1000..9999] range

DISPLAYING ARRAY ELEMENTS6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 2517 1942 5390 3806 3012 2384 8787 5303 8532 6175 3801 5351 2792 7316 7428 6781 1425 8943 2871 3439 4729 8397 7501 5825 9903 3555 8952 1831 7010 5108 1396 5582 7099 7758 9318 4580 3412 1691 4350 8728 4774 3644 1054 1508 7380 5599 1158 3655 2594 2497 4294 4087 7553 8318 2583 1499 6370 6773 4990 2519 8076 8121 2918 6056 3188 3826 7849 3992 9552 6875 1003 5900 9832 3364 8275 1544 3409 5055 7398 9116 8687 1439 6953 3367 9551 4141 7715 5466 1174 6677

Press the <enter> key to continue...

DISPLAYING ARRAY ELEMENTS1003 1054 1158 1174 1396 1425 1439 1499 1508 1544 1691 1828 1831 1942 2084 2375 2384 2497 2501 2517 2519 2583 2594 2792 2871 2918 3012 3188 3364 3367 3409 3412 3439 3555 3644 3655 3801 3806 3826 3992 4055 4087 4141 4294 4350 4580 4729 4774 4990 5055 5108 5303 5351 5389 5390 5466 5582 5599 5825 5900 6056 6080 6175 6251 6370 6677 6773 6781 6875 6953 7010 7099 7316 7380 7398 7428 7501 7553 7715 7758 7849 8076 8121 8275 8318 8397 8532 8687 8728 8787 8943 8952 9116 9241 9318 9551 9552 9802 9832 9903

Page 568 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 45: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

13.7 Understanding The Binary Search

We are now ready to return to the all-important business of searching. It was mentioned that searching can benefit from sorting, which is why the whole sorting issue became a big deal in the first place. We now have sorted a variety of ways and this means you are anxious to see what you have gained with all this newly found knowledge.

Imagine a thick telephone book. It has 2000 pages. Do you perform a sequential search when you look for a phone number? Such an approach would be horrendous. You approximate the location of the number and open the book. Now there are three possibilities. You have the correct page; the number is on an earlier page; the number is on a later page. You repeat the process of guessing until you find the correct page.

Now imagine that you have a really bad guessing ability. Who knows, maybe you are alphabetically challenged. All you know how to do is find mid point pages by splitting pages in two. So consider the following arithmetic.

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.

Chapter XIII Algorithms Page 569

Page 46: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

This splitting in half is telling us that even with a bad guessing techniques, and splitting each section in half, it will at most require looking at 11 pages for a book with 2000 pages. This is a worst case scenario. With a sequential search starting at page 1, it will take looking at 2000 pages in a worst case scenario. This is quite a difference, and this difference is the logic used by the Binary Search.Let us apply this logic to a list of 12 numbers and see what happens when we search for a given element in figure 13.21

Figure 13.21

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14]10 15 20 25 30 35 40 45 50 55 60 65 70 75 80

Suppose we wish to find element 55.

We take the first and last element index and divide by 2. (0 + 14)/2 = 7

We check list[7].

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14]10 15 20 25 30 35 40 45 50 55 60 65 70 75 80

We see that list[7] = 45 and realize that the List[0]..List[7] can now be ignored.

We continue the search with List[8]..List[14].

We take the first and last element index and divide by 2. (8 + 14)/2 = 11

We check List[11].

We see that List[11] = 65 and realize that the List[11]..List[14] can be ignored.

We continue the search with List[8]..List[10].

We take the first and last element index and divide by 2. (8 + 10)/2 = 9

We check List[9].

We see that List[9] = 55. We have found the search item.

Page 570 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Page 47: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

Binary Search Algorithm

The Binary Search only works with sorted lists.

Start by making the smallest index small and thelargest 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 searchItem is greater you have a new small,otherwise you have a new large

Repeat the same process.Continue the process until the searchItem is found orlarge becomes less than small.

The Binary Search is more complicated than the Linear Search, but the extra work is worth it. A list of one million elements is quite large and even such a large list requires only at most 24 comparisons with a Binary Search. The Linear Search may take up to 1,000,000 comparisons in a worst case scenario, when the element is at the end of the list.

You will not be shown an example of a Binary Search algorithm in Java code in this course. You will see it in the AP Computer Science class, which you may take next school year. You also may remember that there was a binarySearch method in the Arrays class back in Chapter 11. Even if you cannot yet write your own binary search, nothing prevents you from using one already created.

Chapter XIII Algorithms Page 571

Page 48: vernonmath.comvernonmath.com/wp/wp-content/uploads/2016/02/Text13 …  · Web viewWe need to take a Java break with this chapter. There will be no significant new Java language features

13.8 Summary

An algorithm is a logical sequence of unambiguous instruction to accomplish a specified goal. An algorithm is program language independent. Algorithms can be explained, analyzed and implemented in any program language.

In this chapter the List case study of the array chapter is used to show a variety of algorithms that operate on a list of data. For most of the program examples the List object contains random integers.

The first algorithm is the Linear Search. This algorithm searches a list of data sequentially from start to end to find the requested data. The Linear Search can find data in a list regardless of its sorting order.

Sorting algorithms are both common and important in computer science. Arranging data in a desired order makes it easier and more efficient to find data.

The Bubble Sort is the easiest sorting algorithm. It is also the most inefficient way to sort data. With today's computers this is not a concern for small lists of data of 1000 or less elements. The Bubble Sort compares adjacent elements and swaps them if they are not in the proper sequence.

Inserting an array element in an existing array requires that you first use a search routine to find the correct insert location. This is followed by shifting array elements to open up space for the new array element. Special consideration needs to be given that the list has additional memory available for the insertion of a new array element.

Deleting an array element is quite similar to the insertion process. The primary difference is the possibility that the delete item does not exist in the list. Like insertion, a search must be processed first to find the delete item. Now array elements need to be shifted to eliminate the delete element.

Page 572 Exposure Java 2015, Pre-AP®CS Edition 05-22-15