01969 PPT Ch09(Adv Arrays)

download 01969 PPT Ch09(Adv Arrays)

of 86

Transcript of 01969 PPT Ch09(Adv Arrays)

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    1/86

    Programming Logic andDesign

    Fifth Edition, Comprehensive

    Chapter 9Advanced Array Manipulation

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    2/86

    Programming Logic and Design, Fifth Edition, Comprehensive 2

    Objectives

    Learn about the need for sorting data

    Swap two values in computer memory

    Pass by value.vs. Pass by reference(address)

    Understand the bubb le sor t Understand the insertion so rt

    Understand the select ion so rt

    Use mult id imensional arrays

    Use a bu il t-inArrayclass

    Use indexed fi les

    Use a linked l ist

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    3/86

    Programming Logic and Design, Fifth Edition, Comprehensive 3

    Understanding the Need forSorting Records

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

    Random order: records are in the order in whichthey were added

    Sorting: placing the records in order, based on thevalues in one or more fields

    Ascending order: arranged from lowest to highest Descending order: arranged from highest to lowest

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    4/86

    Programming Logic and Design, Fifth Edition, Comprehensive 4

    Understanding the Need forSorting Records (continued)

    Median value: is the middle item when values arelisted 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 sys tem dependent(ASCII or EBCDIC or Unicode)

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    5/86

    Programming Logic and Design, Fifth Edition, Comprehensive 5

    Understanding How to SwapTwo Values

    Swapping two values central to most sortingtechniques

    When swapping two variables, you reversetheir

    position Use a temporary variable named tempto hold onevalue.

    publ ic static void swapScores (f loat [ ] scores)

    { f loat temp ;temp = scores[0];

    scores[0] = scores[1];

    scores[1] = temp; }

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    6/86

    How to Swap Two Array Values

    publ ic stat ic vo id main(Str ing [ ] args ) {

    f loat [ ] sco res = new float [3] ;

    scores[0] = 91.5;

    scores[1] = 84.8; scores[2] = 99.0;

    swapSco res (scores [ ] );

    }

    pub l ic static void swapScores (f loat [ ] scores)

    { f loat temp;temp = scores[0];

    scores[0] = scores[1];

    scores[1] = temp; }

    Programming Logic and Design, Fifth Edition, Comprehensive 6

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    7/86

    Programming Logic and Design, Fifth Edition, Comprehensive 7

    Figure 9-1 Program segment that swaps two values

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    8/86ITP 120 Java Programming I8

    Patrick Healy

    Class #5 Arrays

    Patrick Healy

    Class #5 ArraysAlgorithms forSorting Arrays

    n Some of the many algorithms that exist for sorting arrays are:

    l Selection sortl Bubble sort Shell sort (similar to a bubble sort)

    l Insertion sort

    l Quick sort

    l Merge sort

    l Bucket sort

    n These algorithms are typically studied in a data structures class,

    but we will look at only the selection , insertion, and bubble sorts.

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    9/86

    Programming Logic and Design, Fifth Edition, Comprehensive 9

    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 ascendingsort, after a complete pass through

    the list: Largest item sinks to the bottom

    Smallest item bubbles to the top

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    10/86

    Programming Logic and Design, Fifth Edition, Comprehensive 10

    Figure 9-2 The SortScores program

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    11/86

    Programming Logic and Design, Fifth Edition, Comprehensive 11

    Figure 9-3 The fillArray()method

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    12/86

    Programming Logic and Design, Fifth Edition, Comprehensive 12

    Figure 9-4 The incomplete sortArray()method

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    13/86

    Programming Logic and Design, Fifth Edition, Comprehensive 13

    Figure 9-5 The swap() method

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    14/86

    Programming Logic and Design, Fifth Edition, Comprehensive 14

    Using a Bubble Sort (continued)

    Start with x = 0, compare first pair and swapscore[0] = 90score[1] = 85

    score[2] = 65

    score[3] = 95

    score[4] = 75

    score[0] = 85

    score[1] = 90

    score[2] = 65

    score[3] = 95

    score[4] = 75

    x = 1, compare with next and swap

    score[0] = 85

    score[1] = 90score[2] = 65

    score[3] = 95

    score[4] = 75

    score[0] = 85

    score[1] = 65score[2] = 90

    score[3] = 95

    score[4] = 75

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    15/86

    Programming Logic and Design, Fifth Edition, Comprehensive 15

    Using a Bubble Sort (continued)

    With x = 2, no swap neededscore[0] = 85score[1] = 65

    score[2] = 90

    score[3] = 95

    score[4] = 75

    score[0] = 85

    score[1] = 65

    score[2] = 90

    score[3] = 95

    score[4] = 75

    x = 3, compare with x = 4 and swap

    score[0] = 85

    score[1] = 65score[2] = 90

    score[3] = 95

    score[4] = 75

    score[0] = 85

    score[1] = 65score[2] = 90

    score[3] = 75

    score[4] = 95

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    16/86

    Programming Logic and Design, Fifth Edition, Comprehensive 16

    Figure 9-6 The completed sortArray() method

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    17/86

    Programming Logic and Design, Fifth Edition, Comprehensive 17

    Using a Bubble Sort (continued)

    Use nested loops for sort ing an array

    Inner loop m akes the pair compar ison s

    Greatest number of compar isons is one less than

    the number of array elements

    Outer loop con tro ls the number of times to

    process the list

    One less than the number of array elements

    Cl #5 ACl #5 A

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    18/86ITP 120 Java Programming I

    18Patrick Healy

    Class #5 Arrays

    Patrick Healy

    Class #5 ArraysBubble Sort in Java

    n Bubble sort: Sorts an array into ascending or descending order

    and works by making several passes through the array.n During each pass, the smaller values rise and the larger values

    sink.

    n During each pass, successive elements of the array are

    compared and swapped if necessary to ensure that the smallervalues rise and the larger values drop.

    n 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.

    Cl #5 ACl #5 A

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    19/86

    ITP 120 Java Programming I19

    Patrick Healy

    Class #5 Arrays

    Patrick Healy

    Class #5 ArraysBubble 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/sort/Sort2-E.html

    http://www.cs.oswego.edu/~mohammad/classes/csc241/samples/sort/Sort2-E.htmlhttp://www.cs.oswego.edu/~mohammad/classes/csc241/samples/sort/Sort2-E.htmlhttp://www.cs.oswego.edu/~mohammad/classes/csc241/samples/sort/Sort2-E.htmlhttp://www.cs.oswego.edu/~mohammad/classes/csc241/samples/sort/Sort2-E.htmlhttp://www.cs.oswego.edu/~mohammad/classes/csc241/samples/sort/Sort2-E.htmlhttp://www.cs.oswego.edu/~mohammad/classes/csc241/samples/sort/Sort2-E.html
  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    20/86

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

    20

    Bubble Sort

    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 4 5 8 1 9

    2 4 5 8 1 9

    2 4 5 1 8 9

    (b) 2nd pass

    2 4 5 1 8 9

    2 4 1 5 8 9

    (c) 3rd pass

    2 1 4 5 8 9

    (d) 4th pass

    2 9 5 4 8 1

    (e) 5th pass

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

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    21/86

    Programming Logic and Design, Fifth Edition, Comprehensive 21

    Figure 9-6 The displayArray()method

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    22/86

    Programming Logic and Design, Fifth Edition, Comprehensive 22

    Sorting a List of Variable Size

    Use a variable to ho ld the number of arrayelements

    Declare the array w ith a large fixed s ize

    Coun t the number of input elements

    Store the coun t in variable

    Use the variable to determ ine size of array

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    23/86

    Programming Logic and Design, Fifth Edition, Comprehensive 23

    Figure 9-8 Score sorting application in which number of elements to sort can vary

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    24/86

    Programming Logic and Design, Fifth Edition, Comprehensive 24

    Figure 9-8 Score sorting application in which number of elements to sort can vary(continued)

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    25/86

    Programming Logic and Design, Fifth Edition, Comprehensive 25

    Refining the Bubble Sort by ReducingUnnecessary 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.

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    26/86

    Programming Logic and Design, Fifth Edition, Comprehensive 26

    Figure 9-9 Flowchart and pseudocode forsortArray()methodusing pairsToCompare variable

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    27/86

    Programming Logic and Design, Fifth Edition, Comprehensive 27

    Refining the Bubble Sort byEliminating Unnecessary Passes

    Need one fewer pass than the number ofelements 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

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    28/86

    Programming Logic and Design, Fifth Edition, Comprehensive 28

    Figure 9-10 Flow char t and ps eudocod e forsortArray()methodus ingswitchOccurred var iable

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    29/86

    Programming Logic and Design, Fifth Edition, Comprehensive 29

    Figure 9-10 Flow char t and ps eudocod e forsortArray()methodus ingswitchOccurredvar iable (cont inu ed)

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    30/86

    Programming Logic and Design, Fifth Edition, Comprehensive 30

    Using an Insertion Sort

    Bubble sor tis one of the least eff icientsortingmethods

    Insertion sort requires fewercomparisons

    This sort compares a pair of elements If an element is smaller than the previous one, searchthe array backward from that point Insert this element at the proper location

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    31/86

    Insertion Sort in Javaint [ ] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted

    The insertion sortalgorithm sorts alist of values byrepeatedly insertingan unsorted elementinto a sorted sublistuntil the whole listis sorted.

    2 9 5 4 8 1 6Step 1: Initially, the sorted sublist contains thefirst element in the list. Insert 9 to the sublist.

    2 9 5 4 8 1 6Step2: The sorted sublist is {2, 9}. Insert 5 to the

    sublist.

    2 5 9 4 8 1 6Step 3: The sorted sublist is {2, 5, 9}. Insert 4 to

    the sublist.

    2 4 5 9 8 1 6Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8to the sublist.

    2 4 5 8 9 1 6Step 5: The sorted sublist is {2, 4, 5, 8, 9}. Insert

    1 to the sublist.

    1 2 4 5 8 9 6Step 6: The sorted sublist is {1, 2, 4, 5, 8, 9}.Insert 6 to the sublist.

    1 2 4 5 6 8 9Step 7: The entire list is now sorted

    animation

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    32/86

    Insertion Sort in Java(Click the mouse to show the animation steps)

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

    2 5 9 4 8 1 6

    2 4 5 8 9 1 6

    1 2 4 5 8 9 6

    2 4 5 9 8 1 6

    1 2 4 5 6 8 9

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

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    33/86

    Programming Logic and Design, Fifth Edition, Comprehensive 33

    Figure 9-12 Insertion sort

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    34/86

    Insertion Sort in Java

    // InsertionSort.java Sort some numbers using Insertion sortpublic class InsertionSort {

    public static void main (String [ ] args){// Initialize the listdouble[] myList = {5.0, 4.4, 1.9, 2.5, 3.4, 3.5, 89.7, 6.6, 75.2};

    // Print the original listSystem.out.println("Array myList BEFORE Insertion Sort:\n");printList(myList);

    insertionSort(myList); // Sort the list

    // Print the sorted listSystem.out.println();System.out.println("Array myList AFTER Insertion Sort:\n");printList(myList);

    } // End of main method

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    35/86

    Insertion Sort in Java (contd)

    static void printList(double[ ] list) // Print numbers

    {

    for (int i=0; i

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    36/86

    Actual Insertion Sort Method in Java

    // The Insertion Sort method for sorting the numberspublic 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 ArraysClass #5 Arrays

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    37/86

    ITP 120 Java Programming I37

    Patrick Healy

    Class #5 Arrays

    Patrick Healy

    Class #5 ArraysThe Selection Sort

    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 endl 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

    n Consider this list of the integer numbers: 2 9 5 4 8 1 6

    After 1st iteration 2 6 5 4 8 1 | 9

    After 2nd iteration 2 6 5 4 1 | 8 9

    After 3rd iteration 2 1 5 4 | 6 8 9

    After 4th iteration 2 1 4 | 5 6 8 9After 5th iteration 2 1 | 4 5 6 8 9

    After 6th iteration 1 | 2 4 5 6 8 9

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    38/86

    Programming Logic and Design, Fifth Edition, Comprehensive 38

    Using a Selection Sort

    Selection sort: Sort two variables and s tore thesmallest value and its po si t ion in the array

    Store f irst element value and its pos i t ion invariables

    Compare it to the next element

    If next element is smaller, pu t i ts value and pos it ionin th e variables

    Con tinue un t i l end of array, at which t ime thesmallest value and its pos i t ion are in the variables

    Swap the f irst element value and posi t ion w ith theelement and pos i t ion s tored in the variables

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    39/86

    Programming Logic and Design, Fifth Edition, Comprehensive 39

    Using a Selection Sort (continued)

    Start at the second element in the array andrepeat the process

    Con tinue un t i l al l elements except the last havebeen designated as the start ing poin t

    After making one fewer pass than the number ofelements , the array is so rted

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    40/86

    Programming Logic and Design, Fifth Edition, Comprehensive 40

    Figure 9-13 A selection sort method

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    41/86

    Programming Logic and Design, Fifth Edition, Comprehensive 41

    Figure 9-13 A selection sort method (continued)

    Class #5 ArraysClass #5 Arrays

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    42/86

    ITP 120 Java Programming I42

    Patrick Healy

    Class #5 Arrays

    Patrick Healy

    Class #5 ArraysSelection Sort in Java

    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

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    43/86

    ITP 120 Java Programming I43

    Patrick Healy

    y

    Patrick Healy

    ySelection Sort in Java

    public static void main(String [ ] args ) {

    int [ ] intArray = { 5, 15, 3, 21, 10, 16, 11};// print array before sortingSystem.out.println(Array before sorting: );printArray(int [ ] Array);selectionSorter(int [ ] Array); // Call selection sort

    // print array after sortingSystem.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(); }

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    44/86

    Programming Logic and Design, Fifth Edition, Comprehensive 44

    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

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    45/86

    Programming Logic and Design, Fifth Edition, Comprehensive 45

    Figure 9-14 View of a single-dim ension al array in m emory

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    46/86

    Programming Logic and Design, Fifth Edition, Comprehensive 46

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

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    47/86

    2-Dimensional Table (5 rows x 3 columns)

    oStudio Apt 1-Bedroom Apt 2- Bedroom Apt

    (0,0) $350 (0,1) $390 (0,2) $435

    (1,0) $400 (1,1) $440 (1,2) $480

    (2,0) $475 (2,1) $530 (2,2) $575

    (3,0) $600 (3,1) $650 (3,2) $700

    (4,0) $1000 (4,1) $1075 (4,2) $1150

    Programming Logic and Design, Fifth Edition, Comprehensive 47

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    48/86

    Programming Logic and Design, Fifth Edition, Comprehensive 48

    Figure 9-15 Two-dimensionalrent array based o n rent sch edule in Table 9-1

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    49/86

    Programming Logic and Design, Fifth Edition, Comprehensive 49

    Figure 9-16 A program that determines rents

    Class #5 ArraysClass #5 Arrays

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    50/86

    ITP 120 Java Programming I50

    Patrick HealyPatrick Healy

    Copying Arrays in Java ( 3 ways to copy )

    n Use a loop to copy individual array elements

    for (int I = 0; I < sourceArray.length; I++)targetArray[ I ] = sourceArray[ I ];

    n Use the clone method in the java.lang. Object class

    int [ ] targetArray = (int [ ]) sourceArray.clone();

    n Use the static arraycopy method in thejava.lang.System class

    arraycopy(sourceArray, src pos, targetArray, tar pos, length);

    Class #5 ArraysClass #5 Arrays

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    51/86

    ITP 120 Java Programming I51

    Patrick HealyPatrick Healy

    Copying Arrays using the arraycopy method

    n 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

    Class #5 ArraysClass #5 Arrays

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    52/86

    ITP 120 Java Programming I52

    Patrick HealyPatrick Healy

    Multidimensional ArraysDeclaring 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

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    53/86

    ITP 120 Java Programming I53

    Patrick HealyPatrick Healy

    Multidimensional Array Illustrations

    0 1 2 3 4

    0

    7

    0 1 2 3 4

    1

    2

    3

    4

    0

    1

    2

    3

    4

    matrix[2][1] = 7;matrix = newint[5][5];

    3

    7

    0 1 2

    0

    1

    2

    int[][] array = {

    {1, 2, 3},

    {4, 5, 6},

    {7, 8, 9},

    {10, 11, 12}

    };

    1 2 3

    4 5 6

    8 9

    10 11 12

    Class #5 ArraysClass #5 Arrays

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    54/86

    ITP 120 Java Programming I54

    Patrick HealyPatrick Healy

    Declaring, Creating, and Initializing Using Shorthand Notations

    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;

    Class #5 ArraysClass #5 Arrays

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    55/86

    ITP 120 Java Programming I55Patrick HealyPatrick Healy

    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

    Class #5 ArraysClass #5 Arrays

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    56/86

    ITP 120 Java Programming I56Patrick HealyPatrick Healy

    Ragged ArraysEach row in a two-dimensional array is itself an array. So,

    the rows can have different lengths. Such an array isknown as a ragged array. For example,

    int[ ][ ] matrix = {

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

    {3, 4, 5},

    {4, 5},

    {5}

    };

    Class #5 ArraysClass #5 Arrays

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    57/86

    ITP 120 Java Programming I57Patrick HealyPatrick Healy

    Ragged Arrays Lengths of Ragged Arraysint[ ][ ] matrixArray = {

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

    {2, 3, 4, 5},

    {3, 4, 5},

    {4, 5},

    {5}

    };

    matrixArray[0].length is 5 matrixArray[4] .length is 1matrixArray[1].length is 4

    Class #5 ArraysClass #5 Arrays

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    58/86

    ITP 120 Java Programming I 58Patrick HealyPatrick Healy

    Ragged Arrays: Creating Ragged ArraysIf you dont know the values in a ragged array in advance,

    you can create a ragged array using the syntax whichfollows:

    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

    Class #5 ArraysClass #5 Arrays

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    59/86

    ITP 120 Java Programming I 59Patrick HealyPatrick Healy

    Ragged Arrays: Creating RaggedArrays

    Now, you can assign random values to the array using thefollowing syntax:

    for (int row = 0; row

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    60/86

    ITP 120 Java Programming I 60Patrick HealyPatrick Healy

    Multidimensional Arrays (N-Dimensional)

    The general syntax for declaring an n-dimensional array is:

    datatype [ ][ ][ ] arrayName = newdatatype[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]

    Class #5 ArraysClass #5 ArraysM lti Di i l A

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    61/86

    ITP 120 Java Programming I 61Patrick HealyPatrick Healy

    Multi-Dimensional Arrays

    n 2-Dimensional Arrays are often used to represent tables or

    matrices consisting of rows and colums of values.

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

    Class #5 ArraysClass #5 ArraysM lti Di i l A

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    62/86

    ITP 120 Java Programming I 62Patrick HealyPatrick Healy

    Multi-Dimensional Arrays

    n 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

    Class #5 ArraysClass #5 ArraysM lti Di i l A

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    63/86

    ITP 120 Java Programming I 63Patrick HealyPatrick Healy

    Multi-Dimensional Arrays

    n 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

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    64/86

    Programming Logic and Design, Fifth Edition, Comprehensive 64

    Using a Built-In ARRAY Class

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

    Modern programming languages provide an Arrayclass

    Newer languages have vast libraries Contain built-in methods

    Most useful Array class contains overloadedversions of each method call for each data type Different versions ofsort() methods for numeric and

    string elements

    If noArrayclass avai lable, w ri te your own

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    65/86

    Programming Logic and Design, Fifth Edition, Comprehensive 65

    Table 9-2 Typical useful methods of the Array class

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    66/86

    Programming Logic and Design, Fifth Edition, Comprehensive 66

    Using Indexed Files

    Large data file to be accessed in sorted order; usuallyone field determines the sorting

    Key field: field whose contents make the recordunique

    Indexing records: a list of key fields is paired withcorresponding file position

    Sorting indexes is fasterthan physically sortingactual records

    Random-access storage device: records accessedin any order

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    67/86

    Programming Logic and Design, Fifth Edition, Comprehensive 67

    Table 9-3 Sample index

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    68/86

    Programming Logic and Design, Fifth Edition, Comprehensive 68

    Using Indexed Files (continued)

    Address: location within computer memory or storage

    Every data record on the disk has an address

    Index: holds phys ical addresses and key f ield

    values Data file is in some kind ofphysical 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 physical ly removed

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    69/86

    Programming Logic and Design, Fifth Edition, Comprehensive 69

    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 aprevious field Can be traversed both forward and backward

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    70/86

    Programming Logic and Design, Fifth Edition, Comprehensive 70

    Table 9-4 Sample customerl inked l ist

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    71/86

    Programming Logic and Design, Fifth Edition, Comprehensive 71

    Table 9-5 Updated customerl inked l is t

    Class #9 - Abstract Classes and Interfaces

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    72/86

    ITP 120 Java Programming I 72Patrick Healy

    Linked Lists in JavaArrays are useful for storing and managing a set of

    elements of the same type. However, since the length ofan array is fixed once the array is created, you need toknow the length of the array before you create it. Alinked 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 anelement and each node is linked to its next neighbor.

    Thus, a node can be defined as a class as follows:

    Class #9 - Abstract Classes and Interfaces

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    73/86

    ITP 120 Java Programming I 73Patrick Healy

    The Linked List Structurepublic class Node

    { Object element;

    Node next; // Points to next node

    public Node(Object o)

    { element = o; } // Constructor}

    first element

    next

    element

    next

    element

    next

    last

    node1 node2 node n

    Class #9 - Abstract Classes and Interfaces

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    74/86

    ITP 120 Java Programming I 74Patrick Healy

    The Linked List StructureBelow, the variable f i rstrefers to the first node in the

    list, and the variable lastrefers to the last node in thelist. If the list is empty, both are nul l(null addresses)

    first element

    next

    element

    next

    element

    next

    last

    node1 node2 node n

    Class #9 - Abstract Classes and InterfacesLinked Lists: Example for 3 Circle objects

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    75/86

    ITP 120 Java Programming I 75Patrick Healy

    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; // Declare first node

    Node last; // Declare last node

    // 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) objectlast.next = new Node ( new Circle (3)); // Node for 3rd circle object

    last = last.next; // Last node is now Circle (3) object

    Class #9 - Abstract Classes and Interfaces

    Create a Linked List with three Nodes

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    76/86

    ITP 120 Java Programming I 76Patrick Healy

    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 n2n2.next = n3; // link to node n3

    Node first = n1; // Set first node

    Node last = n3; // Set last node

    Class #9 - Abstract Classes and Interfaces

    G i Li k d Li t Add N d

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    77/86

    ITP 120 Java Programming I 77Patrick Healy

    Generic Linked Lists: Add a Node

    element

    next

    element

    next

    current

    first element

    next

    element

    next:null

    last

    element

    next

    New node inserted here

    temp

    To add a new node

    Class #9 - Abstract Classes and Interfaces

    Generic Linked Lists: Remove a Node

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    78/86

    ITP 120 Java Programming I 78Patrick Healy

    Generic Linked Lists: Remove a Node

    Remove a new node

    element

    next

    element

    next

    previous

    first element

    next

    element

    next:null

    last

    Node to be deleted

    current

    After the node isdeleted

    Class #9 - Abstract Classes and InterfacesSample Program: TestLinked List.java

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    79/86

    ITP 120 Java Programming I 79Patrick Healy

    Sample Program: TestLinked List.java

    public class TestLinkedList {

    public static void main(String[ ] args) {

    // Create a linked list

    GenericLinkedList list = new GenericLinkedList();

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

    Class #9 - Abstract Classes and InterfacesTestLinked List.java

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    80/86

    ITP 120 Java Programming I 80Patrick Healy

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

    }

    }

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    81/86

    Programming Logic and Design, Fifth Edition, Comprehensive 81

    Chapter 9 Summary

    Sort data reco rds based on the contents of one ormore f ie lds

    Ascending o rder

    Descending order

    Swap two values

    Tempo rary variable holds one of the values

    Bubble sor t

    Compares pairs

    Swaps w ith i tem below

    Ascending bubble sor t : largest i tem sinks to bot tom

    Smal lest i tem r ises o r bubbles to the top

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    82/86

    Programming Logic and Design, Fifth Edition, Comprehensive 82

    Chapter 9 Summary (continued)

    Bubble sor t(continued) Eliminate unnecessary compar ison s in each pass and

    eliminate unnecessary passes to improve bubble sor t

    Size of l ist to be sorted may vary

    Coun t values to be sorted In i t ia lize array with c oun t var iable when value is known

    Bub ble sor t impro ved by stopping c ompar isons one element

    soon er on each pass

    Bub ble sor t imp roved by stop ping when al l items sor ted

    Flag var iable indicates when any item is swapped

    Ind icates when no i tems sw apped in on e pass throu gh

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    83/86

    Programming Logic and Design, Fifth Edition, Comprehensive 83

    Chapter 9 Summary (continued)

    Insert ion so rtusually requires fewercomparisons

    Pair-wise compar isons are done.

    Locate the out-of-ord er element

    Search array backward to a smaller element Move each element down one

    Insert out-of-order element into open posi t ion

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    84/86

    Programming Logic and Design, Fifth Edition, Comprehensive 84

    Chapter 9 Summary (continued)

    Ascending o rder select ion so rt

    First element assumed to be smallest

    Value and posit ion s tored in variables

    Every subsequent element tested Smallest element found , value and pos it ion

    saved

    Lowest value in f i rst posi t ion after one pass

    through array

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    85/86

    Programming Logic and Design, Fifth Edition, Comprehensive 85

    Chapter 9 Summary (continued)

    One-dimensional array

    Also called single-dimensional array

    Single column of values

    Accessed with a sing le subscr ip t Most object-oriented languages support two-

    dimensional arrays and more

    Both rows and columns

    Two subscripts

    End of Chapter 9

  • 7/28/2019 01969 PPT Ch09(Adv Arrays)

    86/86

    End of Chapter 9Summary

    Arrayclasscontains useful methods formanipulating arrays

    Ind exed fi lesaccess data records in a logicalorder

    Differs from physical order

    Must identify key fieldfor each record

    A l inked l istcontains extra field within every

    record the extra f ield ho lds phys ical address of next

    logical record