SCHAUM’S OUTLINE OF DATA STRUCTURES WITH JAVA This page intentionally left blank SCHAUM’S OUTLINE OF DATA STRUCTURES WITH JAVA Second Edition JOHN R HUBBARD, Ph.D Professor of Mathematics and Computer Science University of Richmond Schaum’s Outline Series McGRAW-HILL New York Chicago San Francisco Lisbon London Madrid Mexico City Milan New Delhi San Juan Singapore Sydney Toronto Copyright © 2007, 2001 by The McGraw-Hill Companies, Inc All rights reserved Manufactured in the United States of America Except as permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher 0-07-150993-3 The material in this eBook also appears in the print version of this title: 0-07-147698-9 All trademarks are trademarks of their respective owners Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark Where such designations appear in this book, they have been printed with initial caps McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs For more information, please contact George Hoare, Special Sales, at george_hoare@mcgraw-hill.com or (212) 904-4069 TERMS OF USE This is a copyrighted work and The McGraw-Hill Companies, Inc (“McGraw-Hill”) and its licensors reserve all rights in and to the work Use of this work is subject to these terms Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited Your right to use the work may be terminated if you fail to comply with these terms THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE McGraw-Hill and its licensors not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom McGraw-Hill has no responsibility for the content of any information accessed through the work Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise DOI: 10.1036/0071476989 Professional Want to learn more? We hope you enjoy this McGraw-Hill eBook! If you’d like more information about this book, its author, or related books and websites, please click here To Anita This page intentionally left blank PREFACE Like other Schaum’s Outlines, this book is intended to be used primarily for self study It is suitable as a study guide in a course on data structures using the Java programming language In American universities, this is typically the second course in the computer science major The book is also serves well as a reference on data structures and the Java Collections Framework The book includes more than 200 detailed examples and over 260 solved problems The author firmly believes that programming is learned best by practice, following a well-constructed collection of examples with complete explanations This book is designed to provide that support This second edition is a major improvement over the original 2001 edition Most of the chapters have been completely rewritten Three entirely new chapters have been added, on object-oriented programming, linked structures, and the Java Collections Framework Java 6.0 is used throughout the book, with special attention to these new features of the language: • The Scanner class • The StringBuilder class • Formatted output, including the printf() method • The enhanced for loop (also called the for-each loop) • Static imports • enum types • Variable length parameter lists • Autoboxing • Generic classes • The Deque , ArrayDeque , EnumSet , and EnumMap classes, and the Queue interface in the Java Collections Framework Source code for all the examples, solved problems, and supplementary programming problems may be downloaded from the author’s Web site http://www.mathcs.richmond.edu/~hubbard/books/ I wish to thank all my friends, colleagues, students, and the McGraw-Hill staff who have helped me with the critical review of this manuscript, including Stephan Chipilov and Sheena Walker Special thanks to my colleague Anita Huray Hubbard for her advice, encouragement, and supply of creative problems for this book JOHN R HUBBARD Richmond, Virginia vii This page intentionally left blank = n log n © e¹ ¹ © (Here, “log” means the binary logarithm log2.) Therefore, the algorithm’s worst-case complexity function must be O(n log n) Theorem 14.17 applies only to comparison sorts A comparison sort is an algorithm that sorts elements by comparing their values and then changes their relative positions according to the outcomes of those comparisons All the sorting algorithms outlined previously are comparison sorts In contrast, the following sorting algorithms are not comparisons sorts 270 SORTING [CHAP 14 THE RADIX SORT The radix sort assumes that the sequence’s element type is a lexicographic array of constant size, that is, either a character string type or an integer type Let r be the array element’s radix (e.g., r = 26 for ASCII character strings, r = 10 for decimal integers, r = for bit strings), and let w be the constant width of the lexicographic array For example, for U.S Social Security numbers, d = 10 and w = EXAMPLE 14.11 Sorting Books by Their ISBNs Every book published since the 1970s has been assigned a unique international standard book number (ISBN) These are usually printed at the bottom of the back cover of the book For example, the ISBN for this book is 0071476989 (ISBNs are usually hyphenated, like this: 0-07-147698-9, to distinguish the four separate fields that make up the code.) The last digit is a check digit, computed from the other nine digits Since it can be any of the 10 numeric digits or the letter X, we have that the radix r = 11, while the number of digits d = 10 Algorithm 14.10 The Radix Sort (Precondition: s = {s0 sn–1} is a sequence of n integers or character strings with radix r and width w.) (Postcondition: The sequence s is sorted numerically or lexicographically.) Repeat step for d = up to w – Apply a stable sorting algorithm to the sequence s, sorting only on digit number d A sorting algorithm is said to be stable if it preserves the relative order of elements with equal keys For example, the insertion sort is stable, but the heap sort is not EXAMPLE 14.12 Sorting ISBNs with the radix sort Figure 14.5 shows a sequence of 12 ISBNs and the first four iterations of the radix sort applied to it Figure 14.5 Tracing the radix sort Note how the stability is needed to conserve the work done by previous iterations For example, after the first iteration, 8838650527 precedes 0830636528 because < Both of these keys have the same value in their second least significant digit (digit number d = 1) So on the second iteration, which sorts only on digit number 1, these two keys evaluate as being equal But they should retain their previous relative order because 27 < 28 Stability guarantees that they The columns that have been processed are shaded So after the third iteration, the right-most 3-digit subsequences are sorted: 109 < 13X < 373 < 453 (Note that X stands for the value 10 So 13X numerically means 130 + 10 = 140.) CHAP 14] SORTING 271 EXAMPLE 14.13 The Radix Sort This method assumes that the constants RADIX has WIDTH have been defined For example, for arrays of ints: public static void sort(int[] a) { // POSTCONDITION: a[0] a[j]) { j = k; } } swap(a, n-1, j); sort(a, n-1); } 14.19 The last loop invariant proves correctness So, like the proof for the bubble sort, we need only verify the loop invariants On the first iteration of the main loop (step 1), a[i] is the last element in the array, so the index k of the inner loop runs through every element after a[0] The value of the index j begins at and then changes each time k finds a larger element Since j is always reset to the index of the larger element, a[j] will be the largest element of the array when the inner loop finishes This verifies the first loop invariant On each successive iteration of the outer loop, the index k runs through the remaining unsorted segment of the array, so for the same reason, a[j] will be the largest element of that remaining segment when the inner loop finishes This verifies that the first loop invariant is true on every iteration of the outer loop Since swap(a,i,j) simply interchanges a[i] with a[j], the second loop invariant follows from the first The third loop invariant follows from the second and by mathematical induction During the first iteration of the main loop, the inner loop finds a[j] to be the largest element in the array The swap(a,i,j) puts that largest element in the last location a[i], so a[i] must be >= all the a[j] Prior to the ith iteration of the main loop, we have by the inductive hypothesis that the subarray a[i+1 n) is sorted and all the values in the subarray a[0 i] are smaller than a[i+1] Then after the ith iteration, a[i] is one of those smaller elements, so a[i] d a[i+1] d d a[n-1] 14.20 Again, the proof is essentially the same as that for the corresponding theorem for the bubble sort On the first iteration of the outer i loop, the inner j loop iterates n – times On the second, it iterates n – times This progression continues, for a total of (n – 1) + (n – 2) + · · · + + = n(n – 1)/2 14.21 public static void sort(int[] a, int[] ndx) { for (int i = 1; i < a.length; i++) { int ndxi = ndx[i], j; for (j = i; j > && a[ndx[j-1]] > a[ndxi]; j ) { ndx[j] = ndx[j-1]; } ndx[j] = ndxi; } } CHAP 14] 14.22 SORTING 283 public static void sort(int[] a) { sort(a, a.length); } public static void sort(int[] a, int n) { if (n < 2) { return; } sort(a, n-1); int temp = a[n-1], j; for (j = n-1; j > && a[j-1] > temp; j ) { a[j] = a[j-1]; } a[j] = temp; } 14.23 On the first iteration of the main loop, a[1] is compared with a[0] and interchanged if necessary So a[0] d a[1] after the first iteration If we assume that the loop invariant is true prior to some kth iteration, then it must also be true after that iteration because during it a[k] is inserted between the elements that are less than or equal to it and those that are greater It follows by mathematical induction that the loop invariant is true for all k 14.24 The proof is similar to that for the corresponding theorems for the bubble sort and the selection sort On the first iteration of the outer i loop, the inner j loop iterates once On the second, it iterates once or twice, depending upon whether a[1] > a[2] On the third iteration, the inner j loop iterates at most three times, again depending upon how many of the elements on the left of a[3] are greater than a[3] This pattern continues, so that on the kth iteration of the outer loop, the inner loop iterates at most k times Thus the maximum total number of iterations is + + · · · + (n – 1) = n(n – 1)/2 14.25 In this case, the inner loop will iterate only once for each iteration of the outer loop So the total number of iterations of the inner loop is: + + + · · · +1 + = n – 14.26 For the quick sort pivoting on the last element, the only changes needed are in the partition() method: private static int partition(int[] a, int p, int q) { int pivot = a[q-1], i = p-1, j = q-1; while (i < j) { while (i < j && a[++i] i && a[ j] >= pivot) ; // empty loop if (j > i) { a[i] = a[j]; } } a[j] = pivot; return j; } 14.27 For the quick sort pivoting on median of three elements, the only changes needed are in the partition() method: private static int partition(int[] a, int p, int q) { int m = (p + q)/2; m = indexOfMedian(a, p, m, q-1); swap(a, p, m); // The rest is the same as lines 20-32 in Example 14.9 on page 264 } ...SCHAUM’S OUTLINE OF DATA STRUCTURES WITH JAVA This page intentionally left blank SCHAUM’S OUTLINE OF DATA STRUCTURES WITH JAVA Second Edition JOHN R HUBBARD, Ph.D Professor... defined in the Java Collections Framework (JCF) This library is part of the java. util package The JCF is outlined in Chapter Example 1.6 also uses two new Java features, introduced with Java 5.0:... Fibonacci Numbers 326 INDEX 329 This page intentionally left blank SCHAUM’S OUTLINE OF DATA STRUCTURES WITH JAVA This page intentionally left blank CHAPTER Object-Oriented Programming SOFTWARE