Sorting Partially Sorted Data
- 50Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
How can the textbook email-merging task be generalized, and when would the fact that the data consists of email addresses matter?
50 questions
- 1
How can the textbook email-merging task be generalized, and when would the fact that the data consists of email addresses matter?
Model answer
It can be treated as merging data sets according to a sort key, without relying on the data being email addresses. The email-address format matters if the required ordering depends specifically on a feature such as the domain name.
Explanation
A general program can work with different kinds of data when the sort key is general; domain-based ordering makes the email structure relevant.
- 2
What are the roles of sortedData, unsortedData, and the required result in the example?
Model answer
sortedData is the larger input already ordered by email address, while unsortedData is the smaller input ordered by domain. The result must contain both inputs in email-address order.
Explanation
Identifying the inputs and required output clarifies the sorting problem before choosing an algorithm.
- 3
Why should duplicate email addresses be anticipated, and what duplicate behavior is expected in the example?
Model answer
The lists may contain duplicate addresses because people can make multiple online purchases. If an address appears in both input lists, it remains twice in the merged array but should appear only once in the output file.
Explanation
The example distinguishes the contents of the merged array from the deduplicated file output.
- 4
What are two possible strategies for handling duplicates, and why was removing them during file writing favored?
Model answer
One strategy is to binary-search sortedData for each value in unsortedData; another is to sort the combined data and remove duplicates while writing the file. File-writing removal was favored because it is easy and avoids repeated searches through a large data set.
Explanation
Binary search is cheaper than linear search, but it still takes time, especially when used against a large sorted list.
- 5
Why might removing duplicates only during file writing be the wrong strategy in some cases?
Model answer
If there are very many duplicates, such as nearly all values being duplicates, removing them earlier could be more efficient. The best strategy depends on the data and requires better tools for comparing alternatives.
Explanation
The preferred method can change with the number of duplicates, so the choice involves a trade-off rather than a universally best answer.
- 6
What file format is used for each input, and how does it make array construction more efficient?
Model answer
The file starts with the number of email addresses, followed by one address per line. Knowing the count allows the program to allocate the array directly instead of reading the file once to count entries and again to load them.
Explanation
A count-first format provides the size needed for array allocation before the data is read.
- 7
How should a file with no sorted data be represented under the specified file format?
Model answer
It should contain the value zero as its count, rather than being an empty file.
Explanation
An empty file would violate the format, which requires a count before the data lines.
- 8
Which boundary cases should be tested for the two input lists?
Model answer
Test cases should include no sorted data, no unsorted data, one element in either list, and one element in both lists.
Explanation
These cases check that the algorithm and file handling work at the limits of the input sizes.
- 9
Why might simply placing all data in one array and calling Arrays.sort be reasonable in one situation but unsuitable in another?
Model answer
It is a short and simple implementation when minimizing programming time is the main constraint. It is less suitable when the lists are enormous and efficiency matters, because it does not exploit the existing sorted order.
Explanation
The best design depends on whether implementation simplicity or efficient use of the already sorted data is the primary constraint.
- 10
How does adapting selection sort use the fact that one input is already sorted?
Model answer
At each position, the algorithm finds the smallest remaining value by comparing the current candidate with the next value in sortedData and with values in unsortedData. It then places the minimum at the current position.
Explanation
The sorted input can be searched in a structured way while the algorithm selects successive minimum values.
- 11
What happens to the sorted and unsorted portions when the adapted selection sort begins making swaps?
Model answer
Values from the sorted portion can be moved into positions occupied by the unsorted portion, so the original sorted region becomes mixed. However, the ordering information is not necessarily lost, because moved values are placed among values that are still later in the selection process.
Explanation
The example’s swaps rearrange positions without eliminating the usefulness of the existing order.
- 12
What makes adapting selection sort potentially difficult to implement?
Model answer
It requires separate phases for stepping through the sorted input and searching the unsorted input, which makes the control flow more complex than ordinary selection sort.
Explanation
More complex algorithms are harder to implement correctly, even when their general approach is familiar.
- 13
How would insertion sort be adapted to merge the inputs, and what happens when an unsorted value is already in the correct position?
Model answer
Treat the existing sorted data as the initial sorted portion and insert unsorted values into it one at a time. If an unsorted value is already greater than the values preceding its correct position, it can remain where it is.
Explanation
The approach extends insertion sort’s usual process of adding unsorted values to a sorted group.
- 14
What are the main advantages and disadvantages of adapting insertion sort in this problem?
Model answer
It requires only a small change to insertion sort, such as changing the loop’s starting condition, and it preserves the input data. However, inserting values can require many swaps, which are expensive for very large lists.
Explanation
The method is comparatively easy to code, but its movement of elements can be costly.
- 15
What are the steps in a two-finger merge?
Model answer
First sort the smaller array, then repeatedly compare the next unmerged values from the two sorted arrays and copy the smaller one into a result array. Continue until all values have been merged.
Explanation
The method advances through both sorted inputs in order, selecting the next smallest value at each comparison.
- 16
Why does two-finger merge require a second array, and why was that a serious drawback here?
Model answer
The method stores the merged output separately from the input arrays, requiring another array for the results. For enormous inputs, this can double storage needs and may make the program impractical or unable to run.
Explanation
The extra memory requirement was treated as a deal breaker for this problem.
- 17
Why was selection sort chosen over insertion sort for the described implementation, despite insertion sort being easier to adapt?
Model answer
Both methods use only one array, but selection sort appeared potentially more efficient. Since efficiency was the reason for not simply using Arrays.sort, that consideration favored selection sort despite its greater implementation complexity.
Explanation
The choice prioritized efficiency while acknowledging that insertion sort would be easier to implement.
- 18
Why is knowledge of sorting algorithms useful even when a programming library provides sorting methods?
Model answer
Algorithm knowledge provides reusable building blocks for adapting solutions to new problems. Without knowing selection sort or insertion sort, the programmer might be limited to a general library sort that does not exploit the input’s existing order.
Explanation
Understanding how algorithms work helps programmers choose and adapt them rather than relying only on ready-made methods.
- 19
Why would reading each input file into a separate array conflict with the program’s efficiency goal?
Model answer
The program would need to keep both input arrays and then store their combined data, increasing storage use. Since avoiding excessive storage is a goal, the files are read into one array instead.
Explanation
A separate-array design duplicates storage for data that must ultimately be combined.
- 20
Why does a method that reads both files and returns only one string array have an incomplete return-value design?
Model answer
The caller needs both the combined array and the size of the first, sorted file to know where the two portions meet. Returning only the array does not provide that boundary information.
Explanation
The algorithm needs the original sorted-file size in addition to the combined data.
- 21
What method design was used to provide the file sizes without reading the files again?
Model answer
The main method reads the file sizes, while a separate readFiles method receives scanners for both files and both sizes, then returns one combined string array.
Explanation
Passing the known sizes avoids an additional operation to find the division between the inputs.
- 22
What inputs and output does the described readFiles method have?
Model answer
It takes a scanner for the sorted file, a scanner for the unsorted file, the size of each file, and returns a string array containing both files’ data.
Explanation
The method’s parameters provide the data sources and the counts needed to fill the combined array.
- 23
How does readFiles fill the combined array, and why is its index declared outside both loops?
Model answer
It reads the sorted-file lines first and then the unsorted-file lines, using one index that continues across both loops. Declaring the index outside the first loop lets the second loop resume at the next unused array position.
Explanation
A shared index prevents the second loop from overwriting the values read from the first file.
- 24
What index ranges are used when reading the two files into the combined array?
Model answer
The first loop fills positions from zero up to, but not including, sortedSize. The second continues from sortedSize up to, but not including, sortedSize plus unsortedSize.
Explanation
These ranges place the two inputs consecutively in the result array.
- 25
How can readFiles detect that an input file may be corrupted or have an unexpected number of lines?
Model answer
It can check hasNextLine while reading and then compare the final index with the expected count. A mismatch indicates that the file may have missing or extra data.
Explanation
The expected sizes provide a way to check whether the number of lines read matches the file’s stated count.
- 26
Why should the program notify the user if a file’s contents do not match its stated size?
Model answer
The program may produce incorrect results if a file is corrupted or contains missing or extra data, even if the sorting algorithm itself is correct. The user therefore needs to be warned about the input problem.
Explanation
Input-file errors can cause failure independently of errors in the program’s algorithm.
- 27
Why must the input scanners be closed after reading the files?
Model answer
Closing the scanners releases the files after they have been read. The program explicitly closes both input files once the read operation is complete.
Explanation
File resources should be closed when they are no longer needed.
- 28
What should the save-to-file method write, and which output class is appropriate?
Model answer
It should use a PrintWriter to write the array’s element count first, followed by one element per line, and then close the output file. A Scanner is for input, not output.
Explanation
The output method follows the count-first file format and uses a writer suited to producing text.
- 29
How can the file-writing method remove duplicate values from a sorted array?
Model answer
Write the first value if the array is nonempty, then write each later value only when it differs from the previous value. Because the array is sorted, duplicates appear next to one another.
Explanation
Adjacent comparison is sufficient for detecting duplicate values in sorted data.
- 30
Why must the output count be adjusted when duplicate values are omitted from the file?
Model answer
The count must equal the number of values actually written, not the original array length. It can be calculated as the array length minus the number of duplicate entries.
Explanation
A count that includes omitted duplicates would disagree with the file’s data lines.
- 31
How can the number of duplicate entries be counted while traversing a sorted array?
Model answer
Compare each value with the preceding value and increment the duplicate count when they are equal. The first element is handled separately so the traversal never compares it with an invalid previous index.
Explanation
Sorted order places equal values together, making the preceding element a sufficient comparison.
- 32
Why is the first array element handled separately when writing unique values?
Model answer
The first element has no preceding element, so comparing it with the value at index one less than zero would be invalid. It can be written before the loop, provided the array is nonempty.
Explanation
The special case avoids an out-of-bounds access at the start of the array.
- 33
How does a short-circuit condition help prevent an invalid array access during duplicate checking?
Model answer
A condition first checks that the index is greater than zero and then compares the current value with the previous one. With short-circuit evaluation, the comparison is skipped when the index is zero.
Explanation
The previous-element access is safe only after the index has been shown to be positive.
- 34
Why must string values be compared with equals rather than a numeric comparison operator?
Model answer
Strings are objects, so their contents should be compared with equals. For ordering strings in the sorting algorithm, compareTo is used, with a negative result indicating that the first string comes before the second.
Explanation
The implementation must use string comparison methods rather than numeric relational operators.
- 35
What did the initial output-file test establish, and what did it fail to establish?
Model answer
It showed that the array contents were written and that the output contained the expected number of data elements. It did not show that the data was sorted or that duplicates were handled correctly.
Explanation
Testing file output before implementing sorting checked only the file-writing behavior and contents.
- 36
What did the first sorted-output test reveal after the selection-sort code was added?
Model answer
It showed that the combined values were in sorted order, but it also revealed that duplicate values were still being written to the file.
Explanation
A successful ordering test did not guarantee that the separate duplicate-removal requirement had been implemented.
- 37
What subtle inconsistency exposed an error in the first attempt to count unique output values?
Model answer
The file’s stated count was thirteen even though only twelve data values were written. This showed that the count still included a duplicate that had been omitted from the output.
Explanation
The header count must agree with the actual number of output lines containing data.
- 38
What logic correction was needed when the duplicate counter produced an incorrect count?
Model answer
The counter must increment when adjacent values are equal, not when they are unequal. The duplicate count is then subtracted from the array length to produce the output count.
Explanation
Counting nonduplicates instead of duplicates gives the wrong value to subtract from the total.
- 39
How does the selection-sort implementation choose the initial minimum and the range for its inner search?
Model answer
For each outer-loop position, it initially treats that position as the minimum. If the position is still in the sorted portion, the search begins at the first unsorted position; otherwise, it begins at the next position.
Explanation
The initial candidate is the current position, and the inner loop searches only the remaining candidates relevant to that phase.
- 40
How does the inner loop update the minimum index in the selection-sort implementation?
Model answer
It compares each candidate with the value at the current minimum index and updates the minimum index when the candidate is smaller. For strings, it uses compareTo and tests whether the result is negative.
Explanation
The minimum index records the position of the smallest value found so far.
- 41
Why does the selection-sort implementation use an index to locate the minimum rather than immediately moving each smaller value?
Model answer
The algorithm first searches for the smallest value’s position, then swaps that value into the current position. Tracking the minimum index allows the final exchange to happen after the search.
Explanation
This follows selection sort’s process of selecting a minimum and placing it in its proper position.
- 42
When does the selection-sort implementation perform a swap, and how is the swap carried out?
Model answer
It swaps only when the minimum index differs from the current outer-loop index. A temporary string stores one value while the two array positions exchange values.
Explanation
If the current position already contains the minimum, a swap is unnecessary.
- 43
Why was a direct array-swap utility not used in the described implementation?
Model answer
The swap method mentioned was in the Collections class, and the Arrays class did not provide a corresponding method. The implementation therefore performed the swap with a temporary variable.
Explanation
The available utility did not match the array-based data structure being used.
- 44
Why were comments considered especially useful in the adapted selection-sort code?
Model answer
The algorithm has distinct cases for searching from the sorted boundary or from the next unsorted position, and its structure may look incorrect to readers. Comments clarify why the loops start where they do.
Explanation
Comments help explain non-obvious control flow in a more involved algorithm.
- 45
What role do the outer and inner loops play in the selection-sort implementation?
Model answer
The outer loop visits each position that must receive its next sorted value. The inner loop searches the relevant remaining data for the smallest value to place there.
Explanation
The nested loops implement selection sort’s repeated search-and-place process.
- 46
How can method-by-method development support testing of the overall program?
Model answer
Implementing and testing methods in the order they are used makes it possible to verify parts such as file reading and saving before adding the sorting algorithm. This helps isolate problems when later tests fail.
Explanation
Testing components incrementally provides evidence about which part of the program is working.
- 47
Why is an output file with the expected data count not sufficient evidence that the entire program works?
Model answer
The file may contain the right values and count while still being unsorted or retaining duplicates. Sorting order and duplicate handling must be tested separately.
Explanation
Different requirements need separate checks; success in one does not establish success in the others.
- 48
Why should file-writing code close the output file after writing?
Model answer
The method closes the PrintWriter after all lines have been written so that the output file is properly finished and the file resource is released.
Explanation
Closing the writer completes file output and releases the resource.
- 49
What is the relationship between algorithm details and a programmer’s ability to adapt a solution?
Model answer
Understanding an algorithm’s internal steps allows a programmer to change its starting conditions or data flow to suit a new problem. Merely knowing that an API method exists does not provide the same understanding for adaptation.
Explanation
Algorithms serve as building blocks that can be reshaped to meet particular constraints.
- 50
Why might an implementation use a design that is less elegant than the programmer would prefer?
Model answer
Efficiency constraints can make a less elegant design worthwhile if it meets the program’s storage and performance goals. In this example, passing file sizes to the reading method was accepted to avoid extra work.
Explanation
Design decisions sometimes prioritize efficiency over a more appealing method signature.

Ask anything
We've read this whole study set, so questions about it get the best answers.