You are on page 1of 86

Programming Logic and Design

Fifth Edition, Comprehensive

Chapter 9 Advanced Array Manipulation

Objectives
Learn about the need for sorting data Swap two values in computer memory Pass by value .vs. Pass by reference (address) Understand the bubble sort Understand the insertion sort Understand the selection sort Use multidimensional arrays Use a built-in Array class Use indexed files Use a linked list
Programming Logic and Design, Fifth Edition, Comprehensive 2

Understanding the Need for Sorting Records


Sequential order: records are arranged based on the value in a field
Examples: SSN, employee ID

Random order: records are in the order in which they were added Sorting: placing the records in order, based on the values in one or more fields Ascending order: arranged from lowest to highest Descending order: arranged from highest to lowest

Programming Logic and Design, Fifth Edition, Comprehensive

Understanding the Need for Sorting Records (continued)


Median value: is the middle item when values are listed in order Mean value: is the arithmetic average Computer always sorts based on numeric values
Character data is sorted by its numeric code value A is less than B A has decimal value of 65, B is 66, C is 67, etc. Lowercase a has decimal value of 97, b is 98, etc. Whether A is greater than a is system dependent (ASCII or EBCDIC or Unicode)
Programming Logic and Design, Fifth Edition, Comprehensive 4

Understanding How to Swap Two Values


Swapping two values central to most sorting techniques When swapping two variables, you reverse their position Use a temporary variable named temp to hold one value. public static void swapScores (float [ ] scores) { float temp; temp = scores[0]; scores[0] = scores[1]; scores[1] = temp; }
Programming Logic and Design, Fifth Edition, Comprehensive 5

How to Swap Two Array Values


public static void main(String[ ] args) { float [ ] scores = new float [3]; scores[0] = 91.5; scores[1] = 84.8; scores[2] = 99.0; swapScores (scores [ ] ); } public static void swapScores (float [ ] scores) { float temp; temp = scores[0]; scores[0] = scores[1]; scores[1] = temp; }
Programming Logic and Design, Fifth Edition, Comprehensive 6

Figure 9-1 Program segment that swaps two values


Programming Logic and Design, Fifth Edition, Comprehensive 7

Class #5 Arrays
n

Algorithms forSorting Arrays

Some of the many algorithms that exist for sorting arrays are: l Selection sort l Bubble sort Shell sort (similar to a bubble sort) l Insertion sort l Quick sort l Merge sort l Bucket sort
These algorithms are typically studied in a data structures class, but we will look at only the selection , insertion, and bubble sorts.

Patrick Healy

ITP 120 Java Programming I

Using a Bubble Sort


Bubble sort: one of the simplest sorting techniques Items in a list compared in pairs If an item is out of order, it swaps places with the item below it In an ascending sort, after a complete pass through the list:
Largest item sinks to the bottom Smallest item bubbles to the top

Programming Logic and Design, Fifth Edition, Comprehensive

Figure 9-2 The SortScores program


Programming Logic and Design, Fifth Edition, Comprehensive 10

Figure 9-3 The fillArray() method

Programming Logic and Design, Fifth Edition, Comprehensive

11

Figure 9-4 The incomplete sortArray() method


Programming Logic and Design, Fifth Edition, Comprehensive 12

Figure 9-5 The swap() method


Programming Logic and Design, Fifth Edition, Comprehensive 13

Using a Bubble Sort (continued)


Start with x = 0, compare first pair and swap
score[0] score[1] score[2] score[3] score[4]
score[0] score[1] score[2] score[3] score[4]

= = = = =
= = = = =

90 85 65 95 75
85 90 65 95 75

score[0] score[1] score[2] score[3] score[4]


score[0] score[1] score[2] score[3] score[4]

= = = = =
= = = = =

85 90 65 95 75
85 65 90 95 75
14

x = 1, compare with next and swap

Programming Logic and Design, Fifth Edition, Comprehensive

Using a Bubble Sort (continued)


With x = 2, no swap needed
score[0] score[1] score[2] score[3] score[4]
score[0] score[1] score[2] score[3] score[4]

= = = = =
= = = = =

85 65 90 95 75
85 65 90 95 75

score[0] score[1] score[2] score[3] score[4]


score[0] score[1] score[2] score[3] score[4]

= = = = =
= = = = =

85 65 90 95 75
85 65 90 75 95
15

x = 3, compare with x = 4 and swap

Programming Logic and Design, Fifth Edition, Comprehensive

Figure 9-6 The completed sortArray() method


Programming Logic and Design, Fifth Edition, Comprehensive 16

Using a Bubble Sort (continued)


Use nested loops for sorting an array Inner loop makes the pair comparisons Greatest number of comparisons is one less than the number of array elements Outer loop controls the number of times to process the list
One less than the number of array elements

Programming Logic and Design, Fifth Edition, Comprehensive

17

Class #5 Arrays
n

Bubble Sort in Java

Bubble sort: Sorts an array into ascending or descending order and works by making several passes through the array.
During each pass, the smaller values rise and the larger values sink.

During each pass, successive elements of the array are compared and swapped if necessary to ensure that the smaller values rise and the larger values drop.
At the end of the first pass, the largest value is guaranteed to drop to the very bottom. And the smallest value rise by 1 position.

Patrick Healy

ITP 120 Java Programming I

18

Class #5 Arrays

Bubble Sort in Java

int [ ] array = {2, 9, 5, 4, 8 1 } // Length is 6 public static void bubbleSort( int [ ] array) { int temp; // Temporary hold item for(int pass = 1; pass < array.length; pass++) for (int j = 0; j < array.length 1; j++) if (array[j] > array[j+1]) temp = array[j]; // swap the array elements array [j] = array [j+1]; array [j+1] = temp; } } // End of bubble sort method Click to see animation: http://www.cs.oswego.edu/~mohammad/classes/csc241/samples/sor t/Sort2-E.html
Patrick Healy
ITP 120 Java Programming I
19

Bubble Sort

2 9 5 4 8 1 2 5 9 4 8 1 2 5 4 9 8 1 2 5 4 8 9 1 2 5 4 8 1 9 (a) 1st pass

2 5 4 8 1 9 2 4 5 8 1 9 2 4 5 8 1 9 2 4 5 1 8 9

2 4 5 1 8 9 2 4 5 1 8 9 2 4 1 5 8 9

2 4 1 5 8 9 2 1 4 5 8 9

1 2 4 5 8 9

(b) 2nd pass

(c) 3rd pass

(d) 4th pass

(e) 5th pass

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

20

Figure 9-6 The displayArray() method

Programming Logic and Design, Fifth Edition, Comprehensive

21

Sorting a List of Variable Size


Use a variable to hold the number of array elements Declare the array with a large fixed size Count the number of input elements Store the count in variable Use the variable to determine size of array
Programming Logic and Design, Fifth Edition, Comprehensive 22

Figure 9-8 Score sorting application in which number of elements to sort can vary
Programming Logic and Design, Fifth Edition, Comprehensive 23

Figure 9-8 Score sorting application in which number of elements to sort can vary (continued)
Programming Logic and Design, Fifth Edition, Comprehensive 24

Refining the Bubble Sort by Reducing Unnecessary Comparisons


After the first pass through the array:
Largest item must be at the end of array Second largest item must be at the second-to-last position in the array

It is NOT necessary to compare those two values again On each subsequent pass through the array, stop the pair comparisons one element sooner.

Programming Logic and Design, Fifth Edition, Comprehensive

25

Figure 9-9 Flowchart and pseudocode for sortArray() method using pairsToCompare variable
Programming Logic and Design, Fifth Edition, Comprehensive 26

Refining the Bubble Sort by Eliminating Unnecessary Passes


Need one fewer pass than the number of elements to completely sort the array Can reduce the number of passes if array is somewhat ordered already Use a flag variable to indicate if there were any swaps during a single pass If no swaps, the array is completely sorted

Programming Logic and Design, Fifth Edition, Comprehensive

27

Figure 9-10 Flowchart and pseudocode for sortArray() method using switchOccurred variable
Programming Logic and Design, Fifth Edition, Comprehensive 28

Figure 9-10 Flowchart and pseudocode for sortArray() method using switchOccurred variable (continued)

Programming Logic and Design, Fifth Edition, Comprehensive

29

Using an Insertion Sort


Bubble sort is one of the least efficient sorting methods Insertion sort requires fewer comparisons This sort compares a pair of elements If an element is smaller than the previous one, search the array backward from that point
Insert this element at the proper location

Programming Logic and Design, Fifth Edition, Comprehensive

30

Insertion Sort in Java


int [ ] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted

The insertion sort algorithm sorts a list of values by repeatedly inserting an unsorted element into a sorted sublist until the whole list is sorted.

Step 1: Initially, the sorted sublist contains the first element in the list. Insert 9 to the sublist. Step2: The sorted sublist is {2, 9}. Insert 5 to the sublist. Step 3: The sorted sublist is {2, 5, 9}. Insert 4 to the sublist. Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8 to the sublist. Step 5: The sorted sublist is {2, 4, 5, 8, 9}. Insert 1 to the sublist. Step 6: The sorted sublist is {1, 2, 4, 5, 8, 9}. Insert 6 to the sublist. Step 7: The entire list is now sorted

animation

Insertion Sort in Java


(Click the mouse to show the animation steps)
int [ ] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted array

2 2
2 1

9 5
4 2

5 9
5 4

4 4
8 5

8 8
9 6

1 1
1 8

6
2 9 4 5 5 4 9 8 8 1 1 6 6

6
2 6

1
9

Figure 9-12 Insertion sort


Programming Logic and Design, Fifth Edition, Comprehensive 33

Insertion Sort in Java


// InsertionSort.java Sort some numbers using Insertion sort public class InsertionSort { public static void main (String [ ] args) { // Initialize the list double[] myList = {5.0, 4.4, 1.9, 2.5, 3.4, 3.5, 89.7, 6.6, 75.2}; // Print the original list System.out.println("Array myList BEFORE Insertion Sort:\n"); printList(myList); insertionSort(myList); // Sort the list // Print the sorted list System.out.println(); System.out.println("Array myList AFTER Insertion Sort:\n"); printList(myList); } // End of main method

Insertion Sort in Java (contd)


static void printList(double[ ] list) // Print numbers { for (int i=0; i<list.length; i++) System.out.print(list[i] + " "); System.out.println(); // Print a blank line }

Actual Insertion Sort Method in Java


// The Insertion Sort method for sorting the numbers public static void insertionSort(double[ ] list) { for (int i = 1; i < list.length; i++) { double currentElement = list[i]; int k; for (k = i - 1; k >= 0 && list[k] > currentElement; k--) { list[k+1] = list[k]; // Insert the current element into list[k+1] } list[k+1] = currentElement; } // End of outer for loop } // End of insertionSort method } // End of class InsertionSort (started at top of main method)

Class #5 Arrays
n

The Selection Sort

The selection sort algorithm that sorts a list in ascending order works as follows: l Find the largest item in the list and place it at the end l Remove the last item from further consideration, effectively reducing the list size by 1 l Continue steps 1 and 2 until the list has only 1 item left to sort
Consider this list of the integer numbers: 2 9 5 4 8 1 6

After 1st iteration After 2nd iteration After 3rd iteration After 4th iteration After 5th iteration After 6th iteration
Patrick Healy

2 2 2 2 2

6 5 4 8 1| 9 6 5 4 1|8 9 1 5 4 |6 8 9 1 4|5 6 8 9 1|4 5 6 8 9 1|2 4 5 6 8 9


37

ITP 120 Java Programming I

Using a Selection Sort


Selection sort: Sort two variables and store the smallest value and its position in the array Store first element value and its position in variables Compare it to the next element
If next element is smaller, put its value and position in the variables

Continue until end of array, at which time the smallest value and its position are in the variables Swap the first element value and position with the element and position stored in the variables
Programming Logic and Design, Fifth Edition, Comprehensive

38

Using a Selection Sort (continued)


Start at the second element in the array and repeat the process Continue until all elements except the last have been designated as the starting point After making one fewer pass than the number of elements, the array is sorted

Programming Logic and Design, Fifth Edition, Comprehensive

39

Figure 9-13 A selection sort method


Programming Logic and Design, Fifth Edition, Comprehensive 40

Figure 9-13 A selection sort method (continued)

Programming Logic and Design, Fifth Edition, Comprehensive

41

Class #5 Arrays
n

Selection Sort in Java

public class SortBySelection { // A class SortBySelection public static void selectionSorter( int [ ] list ) // A method in the class { for ( int I = list.length 1; I >= 1; I --) { int currentMax = list[0]; int currentMaxIndex = 0; for (int j = 1; j <= I; j++) { if( currentMaxIndex < list[j] ) { currentMax = list[j]; currentMaxIndex = j; } } // Swap list[i] with list [currentMaxIndex] if necessary if (currentMaxIndex != I ) { list[currentMaxIndex] = list[I]; list[I] = currentMax } } } } ITP 120 Java Programming I Patrick Healy

42

Class #5 Arrays

Selection Sort in Java

public static void main(String [ ] args ) { int [ ] intArray = { 5, 15, 3, 21, 10, 16, 11}; // print array before sorting System.out.println(Array before sorting: ); printArray(int [ ] Array); selectionSorter(int [ ] Array); // Call selection sort // print array after sorting System.out.println(Array after sorting: ); printArray(int [ ] Array); // Print array values } public static void printArray(int [ ] array) { for (int k = 0; k < array.length; k++) System.out.println( + array[k]); System.out.println(); }
Patrick Healy
ITP 120 Java Programming I
43

Using Multidimensional Arrays


One-dimensional (single-dimensional) array
Represents a single list of values

Multidimensional array
A list with two or more related values in each position

Two-dimensional array
Represents values in a table or grid containing rows and columns Requires two subscripts

Three-dimensional array
Supported by many programming languages Requires three subscripts
Programming Logic and Design, Fifth Edition, Comprehensive 44

Figure 9-14 View of a single-dimensional array in memory


Programming Logic and Design, Fifth Edition, Comprehensive 45

Table 9-1 Rent in $$ schedule based on floor and number of bedrooms

Programming Logic and Design, Fifth Edition, Comprehensive

46

2-Dimensional Table (5 rows x 3 columns)


oStudio Apt (0,0) (1,0) (2,0) (3,0) (4,0) $350 $400 $475 $600 $1000 1-Bedroom Apt (0,1) (1,1) (2,1) (3,1) (4,1) $390 $440 $530 $650 $1075 2- Bedroom Apt (0,2) (1,2) (2,2) (3,2) (4,2) $435 $480 $575 $700 $1150

Programming Logic and Design, Fifth Edition, Comprehensive

47

Figure 9-15 Two-dimensional rent array based on rent schedule in Table 9-1
Programming Logic and Design, Fifth Edition, Comprehensive 48

Figure 9-16 A program that determines rents


Programming Logic and Design, Fifth Edition, Comprehensive 49

Copying Arrays in Java ( 3 ways to copy )


n

Class #5 Arrays

Use a loop to copy individual array elements


for (int I = 0; I < sourceArray.length; I++) targetArray[ I ] = sourceArray[ I ]; Use the clone method in the java.lang. Object class int [ ] targetArray = (int [ ]) sourceArray.clone(); Use the static arraycopy method in the java.lang.System class arraycopy(sourceArray, src pos, targetArray, tar pos, length);

Patrick Healy

ITP 120 Java Programming I

50

Copying Arrays using the arraycopy method


n

Class #5 Arrays

Example:

int [ ] sourceArray = { 16, 24, 31, 45, 62}; // Declare ,create, initialize int [ ] targetArray = new int[sourceArray.length]; // Same lengths System.arraycopy(sourceArray, 0, targetArray,0, sourceArray.length); // Note: The zeros indicate the starting source & target positions

Patrick Healy

ITP 120 Java Programming I

51

Class #5 Arrays

Multidimensional Arrays

Declaring Variables of Multidimensional Arrays and Creating Multidimensional Arrays


int[][] matrix = new int[10][10];

or
int matrix[][] = new int[10][10]; matrix[0][0] = 3; // Insert the number 3 at position row 0, col 0 for (int i=0; i<matrix.length; i++) for (int j=0; j<matrix[i].length; j++) { matrix[i][j] = (int)(Math.random()*1000); }

Patrick Healy

ITP 120 Java Programming I

52

Class #5 Arrays

Multidimensional Array Illustrations

0 1 2 3 4 0 1 2 3 4
matrix = new int[5][5];

0 1 2 3 4 0 1 2 3 4
matrix[2][1] = 7;
7

0 0 1 2 3
1 4

1
2 5

2
3 6 9 12

7
10

8
11

int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };

Patrick Healy

ITP 120 Java Programming I

53

Declaring, Creating, and Initializing Using Shorthand Notations

Class #5 Arrays

You can also use a shorthand notation to declare, create and initialize a two-dimensional array. For example,
Int [ ] [ ] array = {
{1, 2, 3}, {4, 5, 6}, {7, 8, 9},

{10, 11, 12} };

This is equivalent to the following statements:


int[ ] [ ] array = new int[4][3]; // 4 rows, 3 columns

array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;


array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
54

Patrick Healy

ITP 120 Java Programming I

Class #5 Arrays

Lengths of Multidimensional Arrays

int[ ][ ] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; array.length array[0].length would be 3 array[1].length would be 3

array[2].length would be 3
Patrick Healy
ITP 120 Java Programming I
55

Class #5 Arrays

Ragged Arrays

Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example, int[ ][ ] matrix = { {1, 2, 3, 4, 5},

{2, 3, 4, 5},
{3, 4, 5}, {4, 5},

{5}
};
56

Patrick Healy

ITP 120 Java Programming I

Class #5 Arrays

Ragged Arrays Lengths of Ragged Arrays

int[ ][ ] matrixArray = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; matrixArray[0].length is 5 matrixArray[1].length is 4 matrixArray[4] .length is 1

Patrick Healy

ITP 120 Java Programming I

57

Class #5 Arrays

Ragged Arrays: Creating Ragged Arrays

If you dont know the values in a ragged array in advance, you can create a ragged array using the syntax which follows: int[ ][ ] matrixArray = new int[5][ ];
matrixArray[0] = new int[5]; // Row of 5 integers matrixArray[1] = new int[4]; matrixArray[2] = new int[3]; matrixArray[3] = new int[2]; matrixArray[4] = new int[1]; // Row of one integer
58

Patrick Healy

ITP 120 Java Programming I

Class #5 Arrays

Ragged Arrays: Creating Ragged Arrays

Now, you can assign random values to the array using the following syntax: for (int row = 0; row <= matrixArray.length; row++)
for (int col= 0; col <= matrixArray.length; col++) matrixArray[row][col]=(int)(Math.random()*1000); 0 <= random() < 1 // Output is 0.0 and .992

Patrick Healy

ITP 120 Java Programming I

59

Class #5 Arrays

Multidimensional Arrays (N-Dimensional)


The general syntax for declaring an n-dimensional array is: datatype [ ][ ][ ] arrayName = new datatype[intSize1][intSize2][intSize3]; Where intSize1, intSize2, intSize3 are constant expressions yielding positive integers. Example: int [ ] [ ] [ ] myArray = new int [6][7][3]; The syntax to access a member of a n-dimensional array is: arrayName[index1][index2][index3]

Patrick Healy

ITP 120 Java Programming I

60

Class #5 Arrays
n

Multi-Dimensional Arrays

2-Dimensional Arrays are often used to represent tables or matrices consisting of rows and colums of values.
A table with 3 rows & 5 columns may be declared/created as follows int [ ][ ] twoDim = new int[3][5]; // rows first, columns second Or int twoDim[ ] [ ] = new int[3][5]; Or declare it first and create it later as in: int twoDim[ ][ ]; twoDim = new int[3][5];

Patrick Healy

ITP 120 Java Programming I

61

Class #5 Arrays
n

Multi-Dimensional Arrays

The table can also be created and initialized in one step as follows: int [ ][ ] twoDim = { { 2, 5, 6, 1, 12 }, { 7, 9, 3, 5, 15 }, { 21, 0, 7, 6, 3} }; The value at row 2, and column 4 is 5. Referred to as twoDim[1][3]
What will be the value of val in the expression: int val = twoDim[2][4] + 16; // Answer is 3 + 16 = 19

Patrick Healy

ITP 120 Java Programming I

62

Class #5 Arrays
n

Multi-Dimensional Arrays

Printing the twoDim table with nested for loops


for(int I = 0; I < 3; I++) for( j = 0; j < 5; j++) System.out.print(twoDim[ i ][ j ] + ); System.out.println(); // Print a blank line

Patrick Healy

ITP 120 Java Programming I

63

Using a Built-In ARRAY Class


Similar tasks frequently performed on different arrays
Example: filling and sorting

Modern programming languages provide an Array class Newer languages have vast libraries
Contain built-in methods

Most useful Array class contains overloaded versions of each method call for each data type
Different versions of sort() methods for numeric and string elements

If no Array class available, write your own


Programming Logic and Design, Fifth Edition, Comprehensive 64

Table 9-2 Typical useful methods of the Array class

Programming Logic and Design, Fifth Edition, Comprehensive

65

Using Indexed Files


Large data file to be accessed in sorted order; usually one field determines the sorting Key field: field whose contents make the record unique Indexing records: a list of key fields is paired with corresponding file position Sorting indexes is faster than physically sorting actual records Random-access storage device: records accessed in any order
Programming Logic and Design, Fifth Edition, Comprehensive 66

Table 9-3 Sample index


Programming Logic and Design, Fifth Edition, Comprehensive 67

Using Indexed Files (continued)


Address: location within computer memory or storage Every data record on the disk has an address Index: holds physical addresses and key field values Data file is in some kind of physical order
While the Index is sorted in logical order

When a record is removed from an indexed file, the index of the record is deleted from the index file
But the record is NOT physically removed
Programming Logic and Design, Fifth Edition, Comprehensive 68

Using Linked Lists


Linked list: requires one extra field in every record
Holds the physical address of next logical record

Adding a new record:


Search the linked list for the correct logical location Insert the new record
Link the previous record to new record Link the new record to next record in the list

Delete a record by unlinking it More sophisticated linked lists store a next and a previous field
Can be traversed both forward and backward
Programming Logic and Design, Fifth Edition, Comprehensive 69

Table 9-4 Sample customer linked list

Programming Logic and Design, Fifth Edition, Comprehensive

70

Table 9-5 Updated customer linked list

Programming Logic and Design, Fifth Edition, Comprehensive

71

Class #9 - Abstract Classes and Interfaces

Linked Lists in Java


Arrays are useful for storing and managing a set of elements of the same type. However, since the length of an array is fixed once the array is created, you need to know the length of the array before you create it. A linked list can grow or shrink dynamically as needed. (like a vector in the Vector class in Java) A linked list consists of nodes Each node contains an element and each node is linked to its next neighbor. Thus, a node can be defined as a class as follows:

Patrick Healy

ITP 120 Java Programming I

72

Class #9 - Abstract Classes and Interfaces

The Linked List Structure


public class Node { Object element; Node next; { element = o; } } // Points to next node // Constructor public Node(Object o)

node1 first element next

node2 element next

node n element next last

Patrick Healy

ITP 120 Java Programming I

73

Class #9 - Abstract Classes and Interfaces

The Linked List Structure


Below, the variable first refers to the first node in the list, and the variable last refers to the last node in the list. If the list is empty, both are null (null addresses)

node1 first element next

node2 element next

node n element next last

Patrick Healy

ITP 120 Java Programming I

74

Linked Lists: Example for 3 Circle objects


Create 3 nodes to store 3 circle objects with radii of 1, 2, and 3 in a linked list:
Node first; Node last; // Declare first node // Declare last node

Class #9 - Abstract Classes and Interfaces

// Create a node to store the 1st circle object first = new Node(new Circle (1.0)); last = first; // The last node will point to 1st node last.next = new Node ( new Circle (2)); // Node for 2nd circle object last = last.next; // Last node is now Circle (2) object last.next = new Node ( new Circle (3)); // Node for 3rd circle object last = last.next; // Last node is now Circle (3) object
Patrick Healy
ITP 120 Java Programming I
75

Class #9 - Abstract Classes and Interfaces

Create a Linked List with three Nodes (objects)


Node n1 = new Node(new String(Welcome to Java!)); Node n2 = new Node(new JButton(OK)); Node n3 = new Node(new JButton(Cancel)); n1.next = n2; // Link to node n2

n2.next = n3;
Node last = n3;

// link to node n3
// Set last node

Node first = n1; // Set first node

Patrick Healy

ITP 120 Java Programming I

76

Class #9 - Abstract Classes and Interfaces

Generic Linked Lists:


To add a new node
current first element next element next temp element next

Add a Node

element next:null

last

New node inserted here element next

Patrick Healy

ITP 120 Java Programming I

77

Class #9 - Abstract Classes and Interfaces

Generic Linked Lists:


Remove a new node
previous first element next element next current element next

Remove a Node

element next:null

last

Node to be deleted

After the node isdeleted

Patrick Healy

ITP 120 Java Programming I

78

Class #9 - Abstract Classes and Interfaces


public class TestLinkedList {
public static void main(String[ ] args) { // Create a linked list GenericLinkedList list = new GenericLinkedList();

Sample Program: TestLinked List.java

// Add elements to the list


list.addFirst(Jason"); // Becomes index 2 list.addFirst(Carol"); // Becomes index 1 list.addLast(James"); // Becomes last_index - 1 list.addLast(Daniel"); // Becomes last_index list.add("Mary", 2); // Becomes index 3 list.add("Susan", 5); // Becomes index 7 list.add("Chris", 0); // Becomes first index

Patrick Healy

ITP 120 Java Programming I

79

Class #9 - Abstract Classes and Interfaces

TestLinked List.java

// Print the list System.out.println("Strings are added to the linked list are:"); list.printList(); System.out.println(); // Remove elements from the list list.remove("Chris"); // Remove "Chris" list.remove(2); // Remove Jason" list.removeLast( ); // Remove "Susan"
// Print the list System.out.println("The contents of linked list after deletions:"); list.printList(); } }
Patrick Healy
ITP 120 Java Programming I
80

Chapter 9 Summary
Sort data records based on the contents of one or more fields
Ascending order Descending order

Swap two values


Temporary variable holds one of the values

Bubble sort
Compares pairs Swaps with item below Ascending bubble sort: largest item sinks to bottom
Smallest item rises or bubbles to the top
Programming Logic and Design, Fifth Edition, Comprehensive 81

Chapter 9 Summary (continued)


Bubble sort (continued)
Eliminate unnecessary comparisons in each pass and eliminate unnecessary passes to improve bubble sort Size of list to be sorted may vary Count values to be sorted Initialize array with count variable when value is known Bubble sort improved by stopping comparisons one element sooner on each pass Bubble sort improved by stopping when all items sorted Flag variable indicates when any item is swapped Indicates when no items swapped in one pass through

Programming Logic and Design, Fifth Edition, Comprehensive

82

Chapter 9 Summary (continued)


Insertion sort usually requires fewer comparisons
Pair-wise comparisons are done. Locate the out-of-order element Search array backward to a smaller element Move each element down one Insert out-of-order element into open position

Programming Logic and Design, Fifth Edition, Comprehensive

83

Chapter 9 Summary (continued)


Ascending order selection sort
First element assumed to be smallest Value and position stored in variables Every subsequent element tested Smallest element found, value and position saved Lowest value in first position after one pass through array

Programming Logic and Design, Fifth Edition, Comprehensive

84

Chapter 9 Summary (continued)


One-dimensional array
Also called single-dimensional array Single column of values Accessed with a single subscript

Most object-oriented languages support twodimensional arrays and more


Both rows and columns Two subscripts

Programming Logic and Design, Fifth Edition, Comprehensive

85

End of Chapter 9 Summary


Array class contains useful methods for manipulating arrays Indexed files access data records in a logical order
Differs from physical order Must identify key field for each record

A linked list contains extra field within every record


the extra field holds physical address of next logical record
Programming Logic and Design, Fifth Edition, Comprehensive 86

You might also like