The numbers in the array are processed one by one, from left to right. Since the first number is sorted by itself, we will process the numbers in the array from the second.
Analysis of Insertion Sort
Inserting an Element in Place
Sorting a String Array
Sorting Parallel Arrays
To achieve this, the corresponding ID number must also be moved each time a name is moved during the sorting process. Since the name and ID number must be moved "parallel", we say we do a "parallel sort" or we sort "parallel arrays".
Binary Search
At each stage of the search, we limit our search to a part of the list. As long as lo is less than or equal to hi, they define a non-empty part of the search list.
Searching an Array of Strings
If we are comparing words or names and we want the case of the letters in the comparison to be ignored, we can use CompareToIgnoreCase. Here we tell binarySearch to search for "Perrott, Chloe" in locations 5 to 10 of the given array.
Example: Word Frequency Count
If the number of distinct words in the section exceeds MaxWords (50, say), any words after the 50th will be read but not stored, and a message to that effect will be printed. If the word is not found, the place where it should be inserted is returned.
Merging Ordered Lists
Implementing the Merge
Write a program to read a set of n positive integers (assume n < 100) and print their median; n is not specified, but 0 indicates end of data. Write a program to read a set of n positive integers (assume n < 100) and print their mode; n is not specified, but 0 indicates end of data.
BECDCBAADEBACBAEDDBE
Each person votes for an artist by entering the number of the artist (a value from 1 to 10). The median of a set of n numbers (not necessarily distinct) is obtained by arranging the numbers in order and taking the number in the middle.
4325 BECDCBAXDEBACCAEDXBE
Write a program to process the data and print a report consisting of candidate number and the total marks obtained by the candidate in ascending order by candidate number. Two words are anagrams if one word can be formed by rearranging all the letters of the other word, for example: section, notices.
Introduction to Objects
Objects
For our purposes, an object is an entity that has a state and methods to manipulate that state. However, note that an object can also represent an abstract concept, such as a department in a company or a faculty in a university.
Defining Classes and Creating Objects
- Access to Class and Instance Variables
- Initializing Class and Instance Variables
Static methods (class methods); these are loaded once when the class is loaded and can be. When the class is first loaded, no storage is allocated to the instance's (non-static) variables.
Constructors
- Overloading a Constructor
The body of the constructor contains the code that would be executed when the constructor. When the following statement is executed, the instance variables are set to their initial values (specified or default), and the constructor is executed.
Data Encapsulation, Accessor, and Mutator Methods
- An Improved Constructor
- Accessor Methods
- Mutator Methods
Moreover, this is the only way to change its value; the writer of the Part class can guarantee that the value of NumParts will always be the number of objects created. As another exercise, write mutator methods for the price and inStock fields of the Book class.
Printing an Object’s Data
- Using an Instance Method (the Preferred Way)
- Using a Static Method
- Using the toString() Method
If we use an object variable in a context where a string is required, Java will try to call toString from the class to which the object belongs. Since it is not clear what printing an arbitrary object means, Java will look for instructions in the class itself.
The Class Part
- Testing the Class Part
This is the expected output so we are sure the class is working as it should. If for some odd reason the Part class did not provide a printPart or a toString method, a user class could write its own method to print a part's fields.
How to Name Your Java Files
Working with Objects
- Assigning an Object Variable to Another
- Losing Access to an Object
- Comparing Object Variables
It assigns the value 3472 to c; in effect, c (as well as a) now points to the AirFilter object. In fact, when we change the value of a, we lose access to the AirFilter object.
The null Pointer
Of course, p.name and p.price refer to the fields of the argument to equal (b, in the example).
Passing an Object as an Argument
Any change to the object pointed to by p is in fact a change to the original object. We emphasize that the method cannot change the value of the actual argument of (since it does not have access to it), but it can change the object that is pointed to.
Array of Objects
- Finding the Part with the Lowest Price
When printPart is called, 4000 is copied to a temporary location and this location is passed to printPart where it becomes known as p, the name of the formal parameter. Remember that, in general, any element of an array can be treated in the same way as a simple array type variable.
Searching an Array of Objects
When we do this, other classes in the same file can reference the field names directly; for example, we mainly refer to person[n].age and person[n].gender. We can also use a binary search on an array of objects, provided the objects are sorted by the field we want to search.
Sorting an Array of Objects
In getSmallest, we compare the name field of one array element with the name of another array element. In the while condition, we compare the name field of the person being processed (the one at position h) with the field name of the array element.
Using a Class to Group Data: Word Frequency Count
However, the count for an already stored word will increase if it is encountered again.
How to Return More Than One Value: Voting
The following statement will create an object called votes and set votes.valid and votes.spoilt to 0. When we read a valid vote, ++votes.valid adds 1 to votes.valid, and when we read an invalid vote , ++ votes.
What is meant by the state of an object? What determines the state of an object?
Invalid Vote: 8 Invalid Vote: 9 Number of Voters: 30 Number of Valid Votes: 28 Number of Spoiled Votes: 2 Candidate Score Avasa Tawari 6 Saskia Kalicharan 6 Nirvan Singh 4 Torrique Granger 4 Dawren Greenidge 3 Jordon Winner Cato 3 Denise Duncan (s).
Distinguish between a class and an object
Distinguish between a class variable and an instance variable
Distinguish between a class method and an instance method
Distinguish between a public variable and a private variable
To what values are instance fields initialized when an object is created?
What is a no-arg constructor? How does it become available to a class?
What is meant by the term data encapsulation?
Explain the role of the toString() method in Java
Write a program to read names and phone numbers into an array of objects. Request a name and print the person’s phone number
For example, 5/9 are integer values—one for the numerator and the other for the denominator. Test class that creates three Book objects of your choice, prints their data, and prints the number of Book objects created.
Linked Lists
Defining Linked Lists
The data element can actually be one or more fields (depending on what needs to be stored in a node), and next. points to" the next node in the list. In addition to the cells in the list, we need an object variable (eg top) that "points to" the first element in the list.
Basic Operations on a Linked List
- Counting the Nodes in a Linked List
- Searching a Linked List
- Finding the Last Node in a Linked List
If we reach the end of the list and the key does not match any element, we can conclude that the key is not in the list. Recall that the last node in the list is distinguished by its next pointer being null.
Building a Linked List: Adding a New Item at the Tail
A better approach is to hold a pointer (last) to the last node in the list. The printList function loops through the list from the first node to the last and prints the number at each node.
Insertion Into a Linked List
In many situations it is necessary to insert a new node at the beginning of the list. The first statement sets the new node to point to the vertex it points to (which is the first node), and the second statement updates the vertex to point to the new node.
Building a Linked List: Adding a New Item at the Head
You should observe that the code works even if the list is initially empty (that is, if the top part is null). A queue is a linear list in which insertions occur at one end and deletions (see next section) occur at the other end.
Deletion from a Linked List
The node pointed to by curr is effectively no longer in the list - it has been deleted. If we have a large list in which many deletions have occurred, then there will be many "deleted" nodes scattered all over the memory.
Building a Sorted Linked List
Also in this case, the new node must be inserted at the top of the list and become the only node in the list. The insertion of a new node at its correct position in the list is delegated to the addInPlace function.
A Linked List Class
It is the (object) variable, essentially a pointer, which points to the first node in the list. Well, it depends on the kind of elements (the "data") that we want to store in the list.
How to Organize Java Files
We note that if the Node class is needed by another class, it would be best to declare it public and put it in a file called Node.java.
Expanding the LinkedList Class
It finds the last node (for which the next is zero) and makes it point to the new node. The copyList function makes a copy of the list it is called from and returns the copy.
Example: Palindrome
This function should build the linked list in the order in which the characters are typed by the user—each new character is added to the end of the list. The expression phrase.getHeadData() returns the data field (of type NodeData) of the first node in the list.
Saving a Linked List
Note The solution presented was mainly used to demonstrate how linked lists can be manipulated. The problem can be solved more efficiently using character arrays or strings where we have direct access to each character of the given sentence.
Arrays vs. Linked Lists
Storing a Linked List Using Arrays
Merging Two Sorted Linked Lists
Note that this program requires an int version of the NodeData class, which is declared public and stored in the NodeData.java file. It also requires that the join function be placed in the LinkedList class, which is declared public and stored in the LinkedList.java file.
Circular and Two-Way Linked Lists
- Circular Lists
- Two-Way (Doubly Linked) Lists
Write a function that takes three arguments—a pointer to a linked list of integers and two integers n and j—and inserts n after the jth element of the list. Write a function that, given an integer n, converts n to binary and stores each bit in one node of a linked list with the least significant bit at the head of the list and the most significant bit.
The characters in a string are kept in a linked list, one character per note. a) Write a method that, given a pointer to a string and two characters, c1 and c2, replaces all occurrences of c1 with c2. Write a function that, given pointers to two integers, performs a digit-by-digit addition and returns a pointer to the digits of the sum stored in reverse order.
Stacks and Queues
Abstract Data Types
Stacks
- Implementing a Stack Using an Array
- Implementing a Stack Using a Linked List
In this case, we will report that the stack is full and stop the program. To pop an item off the stack, we first check if the stack is empty.
A General Stack Type
- Example: Convert from Decimal to Binary
If we want to implement a stack of integers, we can define the NodeData class as follows. Despite all these changes to Node, Stack and NodeData, the StackTest class of programs P4.1 and P4.2 will work as before if we just change S.push(n) to S.push(new NodeData(n)) and S. pop() to S.pop().getData(), as shown in Program P4.3.
How to Convert from Infix to Postfix
- Evaluating an Arithmetic Expression
We have reached the end of the expression; we pop S, get 40—the result of the expression. Any values can be used as long as they represent the relative precedence of the operators.
Queues
- Implementing a Queue Using an Array
- Implementing a Queue Using a Linked List
If, in doing so, it has the same value as the head, we declare that the queue is full. Didn't we just say that the turn is full when heads and tails have the same value?
Write declarations/functions to implement a queue of double values
When D is done and ready to return, the address at the top of the stack (200) is popped and execution continues at that address. Next, when B is done and ready to return, the address at the top of the stack (300) is popped and execution continues at that address.
An integer array post is used to hold the postfix form of an arithmetic expression such that the following items are true
Recursion
Recursive Definition
Loosely, we can say that an ancestor is a parent, grandparent, great-grandparent, and so on.
Writing Recursive Functions in Java
As a matter of interest, we can also write hcf as an iterative (as opposed to recursive) function, using Euclid's algorithm. Note the number of function calls and additions that must be made, whereas we can compute F(5) straight away using only four additions.
Converting a Decimal Number to Binary Using Recursion
The call to decToBin(1) can now return and the argument at the top of the stack, 3, is reinserted as the value of n. The call to decToBin(3) can now return, and the argument at the top of the stack, 6, is reinserted as the value of n.
Printing a Linked List in Reverse Order
In the first problem, the conversion of n is expressed in terms of n/2; this in turn will be expressed in terms of n/4, and so on, until there is nothing to convert. In the second problem, the print of the list is inversely expressed in terms of the print of a shorter list (the original list minus the first element) in reverse.
Towers of Hanoi
All that remains is to transfer the four disks from C to B using A, which we assume we know how to do. Move disk from A to B Move disk from A to C Move disk from B to C Move disk from A to B Move disk from C to A Move disk from C to B Move disk from A to B.
Writing Power Functions
Merge Sort
The while loop expresses the following logic: as long as we have not processed all the elements in both parts, we enter the loop. When we're done with the first part (i > mid), copy an element from the second part to T.
Counting Organisms
Thus, the cells of organism 1 will be labeled 2, the cells of organism 2 will be labeled 3, and so on. We assume that the data will be read from the orgs.in file and the output will be sent to the orgs.out file.
Finding a Path Through a Maze
- Writing the Program
So from B we go back (we say backtrack) to the position from which we went to B (call this A). The first data line specifies the number of rows and columns of the maze and the coordinates of S.
Write a recursive function, length , that, given a pointer to a linked list, returns the number of nodes in the list
Write a recursive function, sum , that, given a pointer to a linked list of integers, returns the sum of the values at the nodes of the list
If this is not possible, go back and place the first queen in the next column and try again. If this is not possible, go back and place the second queen in the next column and try again.
Random Numbers, Games, and Simulation
Random Numbers
For example, if we want to play Snakes and Ladders, rolling the dice is simulated by having the computer generate a random number from 1 to 6. Let's say we want to create additional problems for the child by using only the numbers 1 to 9.
Random and Pseudorandom Numbers
But suppose we want to simulate the traffic pattern at an intersection with traffic lights. We want to time the lights so that the waiting time in both directions is as short as possible.
Generating Random Numbers by Computer
In Java, we can work with random numbers using the default static random function in the Math; class. However, we can easily write a function that uses randomness to provide random integers from m to n where m < n.
A Guessing Game
Drills in Addition
If r is 0, remainder is a multiple of maxPick+1; the computer picks up maxPick matches, leaving the user in a losing position. In this example, if the residual value is 16 (a multiple of 4), the computer takes 3, leaving the user with 13: a losing position.
Nonuniform Distributions
- Collecting Bottle Caps
Incidentally, we mention that any four numbers can be designated as sunny, any other three as rainy, and the remaining two as cloudy. To simulate an event, we can generate random numbers uniformly distributed in the range 1 to 100.
Simulation of Real-Life Problems
We assume there is one queue; the person at the front of the queue goes to the counter that becomes available first. Traffic lights: What is the best timing of the lights to minimize the average length of queues in all directions.
Simulating a Queue
- Programming the Simulation
Using these assumptions, we can do the simulation to find out how the queue length varies when there are service counters and so on. Review the rest of the table to make sure you understand how these values are obtained.
Estimating Numerical Values Using Random Numbers
- Estimating 5
- Estimating p
If we imagine that the line between 2 and 3 is completely covered with dots, we would expect that the number of dots between 2 and r would be proportional to the length of that segment. Note that the number of dots within the square also includes the number of dots within the circle.
Working with Files
- Input/Output in Java
- Text and Binary Files
- Internal vs. External File Name
- Example: Comparing Two Files
- Input/Output for Binary File
- Binary File of Records
- Random Access Files
Thus, there is a one-to-one correspondence between what is read or written and what is stored in the file. On the other hand, writing it to a text file causes it to be converted to character form and the resulting characters are stored in the file.