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

Slides:



Advertisements
Similar presentations
Lesson 8 Searching and Sorting Arrays 1CS 1 Lesson 8 -- John Cole.
Advertisements

Searching for Data Relationship between searching and sorting Simple linear searching Linear searching of sorted data Searching for string or numeric data.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 9: Searching, Sorting, and Algorithm Analysis
Visual C++ Programming: Concepts and Projects
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11: Sorting and Searching  Searching Linear Binary  Sorting.
Chapter 11 Sorting and Searching. Topics Searching –Linear –Binary Sorting –Selection Sort –Bubble Sort.
1 Lecture 21 Introduction to Sorting I Overview  What is Sorting?  Some Useful Array Handling Methods.  Selection Sort and its Implementation.  Brief.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11 Sorting and Searching.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
Algorithm Efficiency and Sorting
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Searching Arrays Linear search Binary search small arrays
Searching and Sorting Arrays
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Chapter 14: Sorting and searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
CS1101: Programming Methodology Aaron Tan.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Searching and Sorting Arrays.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Chapter 19 Searching, Sorting and Big O
Computer Science Searching & Sorting.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
Chapter 8 Searching and Sorting Arrays Csc 125 Introduction to C++ Fall 2005.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
Array Processing - 2. Objectives Demonstrate a swap. Demonstrate a linear search of an unsorted array Demonstrate how to search an array for a high value.
Algorithm Definition An algorithm is a step-by-step solution to a problem.
Chapter 9 Searching and Sorting
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
1 2. Program Construction in Java. 2.9 Sorting 3 The need Soritng into categories is relatively easy (if, else if, switch); here we consider sorting.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Algorithm Definition An algorithm is a step-by-step solution to a problem.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
The Bubble Sort by Mr. Dave Clausen La Cañada High School.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
3 – SIMPLE SORTING ALGORITHMS
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Visual Classes 1 Class: Bug 5 Objects: All Bug Objects.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Copyright © 2014 Curt Hill Algorithms From the Mathematical Perspective.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
CSCI 51 Introduction to Programming March 10, 2009.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
Algorithm Definition An algorithm is a step-by-step solution to a problem.
First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types.
Algorithm Definition An algorithm is a step-by-step solution to a problem.
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
Searching and Sorting Arrays
PowerPoint Presentation Authors of Exposure Java
PowerPoint Presentation Authors of Exposure Java
Introduction to Search Algorithms
Repetition-Counter control Loop
Objectives At the end of the class, students are expected to be able to do the following: Understand the purpose of sorting technique as operations on.
Describing algorithms in pseudo code
Section 13.1 Introduction.
Searching and Sorting Arrays
Standard Version of Starting Out with C++, 4th Edition
Sub-Quadratic Sorting Algorithms
Searching and Sorting Arrays
Chapter 11 Sorting and Searching
Presentation transcript:

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

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.

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

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.

// 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"); System.out.println("\nGenerating numbers in the [ ] 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 [ ] range\n"); for (int k = 0; k < 100; k++) { int randInt3 = Expo.random(1000,9999); System.out.print(randInt3 + " "); } System.out.println("\n\n"); }

Generating numbers in the [10..99] range Generating numbers in the [ ] range Generating numbers in the [ ] range

Generating numbers in the [10..99] range Generating numbers in the [ ] range Generating numbers in the [ ] range

// 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 [ ] range\n"); for (int k = 0; k < 100; k++) { int randInt1 = rand.nextInt(10000); System.out.print(randInt1 + " "); } System.out.println("\n\n"); }

Generating numbers in the [0..99] range Generating numbers in the [0..999] range Generating numbers in the [ ] range

Generating numbers in the [0..99] range Generating numbers in the [0..999] range Generating numbers in the [ ] range

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

// 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 [ ] 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 [ ] range \n"); for (int k = 0; k < 100; k++) { int randInt1 = random.nextInt(9000) ; System.out.print(randInt1 + " "); } System.out.println("\n\n"); }

Generating numbers in the [10..99] range Generating numbers in the [ ] range Generating numbers in the [ ] range

Generating numbers in the [10..99] range Generating numbers in the [ ] range Generating numbers in the [ ] range

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;

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

Enter minimum random integer ===>> 1000 Enter maximum random integer ===>> 9999 Generating numbers in the [ ] range Enter minimum random integer ===>> 1000 Enter maximum random integer ===>> 9999 Generating numbers in the [ ] range

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

Enter minimum random integer ===>> 1000 Enter maximum random integer ===>> 9999 Generating numbers in the [ ] range Enter minimum random integer ===>> 1000 Enter maximum random integer ===>> 9999 Generating numbers in the [ ] range

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!

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

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

Enter minimum random integer ===>> 1000 Enter maximum random integer ===>> 9999 Generating true random numbers in the [ ] range Generating pseudo random numbers in the [ ] range

Enter minimum random integer ===>> 1000 Enter maximum random integer ===>> 9999 Generating true random numbers in the [ ] range Generating pseudo random numbers in the [ ] range

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.

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.

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

CONSTRUCTING NEW LIST OBJECT WITH DEFAULT VALUES DISPLAYING ARRAY ELEMENTS CONSTRUCTING NEW LIST OBJECT WITH SPECIFIED VALUES DISPLAYING ARRAY ELEMENTS ASSIGNING RANDOM VALUES TO LIST OBJECT DISPLAYING ARRAY ELEMENTS Java1307.java Output

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

CONSTRUCTING LIST WITH VALUES in [0..100] range DISPLAYING ARRAY ELEMENTS CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS CONSTRUCTING LIST WITH VALUES in [0..1] range DISPLAYING ARRAY ELEMENTS CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS

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

Java1309.java Initial Output CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue...

Press the key to continue... CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue...

Press the key to continue... CONSTRUCTING LIST WITH VALUES in [10..19] range DISPLAYING ARRAY ELEMENTS Press the key to continue...

Press the key to continue... CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue...

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

Enter list size ===>> 100 Enter minimum value ===>> 1000 Enter maximum value ===>> 9999 CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue...

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

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.

Enter list size ===>> 100 Enter minimum value ===>> 1000 Enter maximum value ===>> 9999 CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue... Enter search number ===>> is in the list

Enter list size ===>> 100 Enter minimum value ===>> 1000 Enter maximum value ===>> 9999 CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue... Enter search number ===>> is not in the list

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

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.

Enter list size ===>> 100 Enter minimum value ===>> 1000 Enter maximum value ===>> 9999 CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue... Enter search number ===>> is in the list

Enter list size ===>> 100 Enter minimum value ===>> 1000 Enter maximum value ===>> 9999 CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue... Enter search number ===>> is not in the list

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

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.

Enter list size ===>> 100 Enter minimum value ===>> 1000 Enter maximum value ===>> 9999 CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue... Enter search number ===>> is found at index 38

Enter list size ===>> 100 Enter minimum value ===>> 1000 Enter maximum value ===>> 9999 CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue... Enter search number ===>> is not in the list

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

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

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

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

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 Algorithm

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

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.

Enter list size ===>> 100 Enter minimum value ===>> 1000 Enter maximum value ===>> 9999 CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue... DISPLAYING ARRAY ELEMENTS

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

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

Enter list size ===>> 100 Enter minimum value ===>> 1000 Enter maximum value ===>> 9999 CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue... DISPLAYING ARRAY ELEMENTS

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

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.

Enter list size ===>> 100 Enter minimum value ===>> 1000 Enter maximum value ===>> 9999 CONSTRUCTING LIST WITH VALUES in [ ] range DISPLAYING ARRAY ELEMENTS Press the key to continue... DISPLAYING ARRAY ELEMENTS

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.

Binary Search Algorithm 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.

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]

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]

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]

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]

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]

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]

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]

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]