Professional Documents
Culture Documents
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
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
Class #5 Arrays
n
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
11
= = = = =
= = = = =
90 85 65 95 75
85 90 65 95 75
= = = = =
= = = = =
85 90 65 95 75
85 65 90 95 75
14
= = = = =
= = = = =
85 65 90 95 75
85 65 90 95 75
= = = = =
= = = = =
85 65 90 95 75
85 65 90 75 95
15
17
Class #5 Arrays
n
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
18
Class #5 Arrays
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 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
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
20
21
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
It is NOT necessary to compare those two values again On each subsequent pass through the array, stop the pair comparisons one element sooner.
25
Figure 9-9 Flowchart and pseudocode for sortArray() method using pairsToCompare variable
Programming Logic and Design, Fifth Edition, Comprehensive 26
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)
29
30
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
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
Class #5 Arrays
n
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
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
39
41
Class #5 Arrays
n
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
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
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
46
47
Figure 9-15 Two-dimensional rent array based on rent schedule in Table 9-1
Programming Logic and Design, Fifth Edition, Comprehensive 48
Class #5 Arrays
Patrick Healy
50
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
51
Class #5 Arrays
Multidimensional Arrays
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
52
Class #5 Arrays
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
53
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},
Patrick Healy
Class #5 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
Class #5 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
57
Class #5 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
Class #5 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
59
Class #5 Arrays
Patrick Healy
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
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
62
Class #5 Arrays
n
Multi-Dimensional Arrays
Patrick Healy
63
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
65
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
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
70
71
Patrick Healy
72
Patrick Healy
73
Patrick Healy
74
// 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
n2.next = n3;
Node last = n3;
// link to node n3
// Set last node
Patrick Healy
76
Add a Node
element next:null
last
Patrick Healy
77
Remove a Node
element next:null
last
Node to be deleted
Patrick Healy
78
Patrick Healy
79
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
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
82
83
84
85