Sorting Partially Sorted Data
Merging Partially Sorted Data
Problem abstraction and goals
A common data-processing task is to combine two collections when one is already sorted and the other is not. For example, one company’s email-address list may be sorted by email address, while a second company’s list is sorted by domain. The goal is to produce one list sorted by email address.
The problem is not inherently about email addresses. It can be abstracted as merging a sorted data set with an unsorted data set, provided the items can be compared using the desired ordering. A more general program can work with many kinds of comparable values. The data type matters when the ordering itself depends on its structure—for example, sorting email addresses by domain rather than by the full address.
A useful general design principle is to identify which details are essential to the task and which are merely features of the example. This encourages reusable programs and avoids tying an algorithm to one particular application.
The program’s main goals are:
Combine both input lists.
Order all values according to the required key.
Handle repeated values according to a defined output policy.
Use time and storage efficiently, especially when the lists may be very large.
Duplicate values and strategy choices
Internet-shopping data is likely to contain repeated email addresses. A program must decide whether duplicates remain in the combined in-memory data and whether they appear in the output file.
One possible strategy is to check each value in the unsorted list against the sorted list using binary search. Binary search is much cheaper than checking every sorted-list element sequentially, but it still requires work for every value being checked. With a very large sorted list, repeated searches may be costly.
Another strategy is to retain duplicates while sorting and remove them as the output file is written. This is simple because, once the data is sorted, equal values appear next to one another. The output routine can compare adjacent values and write a value only when it differs from the preceding one.
The choice depends on the data and the program’s priorities:
If duplicates are uncommon, removing them during output is straightforward and avoids extra searches.
If duplicates are extremely common, removing them earlier might avoid unnecessary sorting or storage—but that decision requires a more careful comparison of costs.
Algorithm selection should account for input size and data characteristics, not just whether a method is easy to describe.
A data structure and algorithms course develops more formal tools for comparing such trade-offs. Even without those tools, test data should represent realistic conditions, including duplicates.
Input and output file formats
A practical file format begins with the number of data values, followed by one value per line. For example, an input file has:
A line containing the number of addresses.
One email address on each subsequent line.
The count makes it possible to allocate an array of the exact required size before reading the data. Without a count, a program might need to read through the file once to determine its length, allocate storage, and then read it again.
The output file can use the same structure: a count followed by one value per line. If duplicates are removed during output, the count must describe the number of values actually written, not the original array length.
A correctly formatted empty input is not an empty file. It contains a count of zero. This preserves the file format and tells the program that the file contains no data values.
Boundary and error cases
Testing should include cases at the edges of the problem:
The sorted list contains no values.
The unsorted list contains no values.
One list contains exactly one value.
Both lists together contain only one value.
A value occurs in both lists.
Several copies of a value occur.
An input file has fewer or more values than its declared count.
The output contains no unique values to write.
Files can be corrupted or inconsistent. A program can check whether the expected number of lines was actually read and notify the user if the file contents do not match the declared count.
Sorting and merging approaches
Concatenate and sort everything
The simplest approach is to place both lists into one array and call a general-purpose array sort, such as Java’s Arrays.sort.
This method is attractive when implementation time and simplicity are the main constraints. It is easy to write and does not require a specialized merging algorithm.
Its disadvantage is that it ignores the fact that one list is already sorted. When the data sets are enormous, taking advantage of existing order may improve efficiency.
Adapt selection sort
Selection sort repeatedly finds the smallest value in the remaining data and places it at the next position in the result. The partially sorted input creates an opportunity to modify this process:
While the current position is still within the originally sorted portion, the current value is the smallest remaining value from that sorted portion.
The algorithm compares it with values in the unsorted portion.
If an unsorted value is smaller, the two values are swapped.
After the algorithm reaches the unsorted portion, it continues like ordinary selection sort.
Although swaps move values between the portions, the sorted data’s order is not simply lost. A displaced value is moved into the portion that will be searched during later steps, while the untouched values in the original sorted portion remain ordered.
This method uses one combined array. Its implementation requires care because it has two search patterns:
In the original sorted portion, each position is compared with the unsorted portion.
In the unsorted portion, each position is compared with the later positions as in ordinary selection sort.
Selection sort may be more efficient than the insertion-sort adaptation in this situation, but its logic is more involved and therefore easier to implement incorrectly.
Adapt insertion sort
Insertion sort begins with a sorted section and inserts unsorted values into their correct positions within it. The sorted input can serve as the initial sorted section, after which the unsorted values are processed one at a time.
This is a small modification to insertion sort: the algorithm starts with the existing sorted portion rather than starting with only a single sorted value. That makes it relatively easy to adapt.
However, inserting values can require many shifts or swaps. With very large lists, that movement can be expensive. This approach also uses one array, but it may perform substantial work moving values.
Sort the smaller list, then use a two-finger merge
A two-finger merge uses one position marker, or “finger,” for each of two sorted lists:
Sort the smaller, originally unsorted list.
Compare the current values at the heads of the two sorted lists.
Copy the smaller value into a result array and advance the finger for that list.
Continue until one list is exhausted, then copy the remaining values.
Because both lists are sorted, the smallest remaining value must be at one of their current heads. There is no need to inspect every later value in either list. Equal values can be taken from either list while preserving sorted order.
The main drawback is storage: the merged results are written into a separate array. For enormous inputs, this can require roughly twice the array storage and may make the program impractical or impossible to run. This method is a useful merging technique, but the extra space can be a decisive disadvantage.
Comparing the approaches
Concatenate and sort: simplest to implement, but does not exploit the existing sorted order.
Selection-sort adaptation: uses one array and may be more efficient, but its two search phases are more complicated.
Insertion-sort adaptation: uses one array and is easy to adapt, but can perform many shifts or swaps.
Two-finger merge: efficiently combines two sorted lists, but requires a separate result array.
For the described task, selection sort and insertion sort avoid the extra array required by two-finger merging. Selection sort may have an efficiency advantage, while insertion sort is simpler to adapt. If efficiency is the main motivation for avoiding a general-purpose full sort, selection sort is a reasonable choice despite its implementation complexity.
Designing the program’s methods
A method design should meet the program’s requirements without creating unnecessary copies of large data sets.
A tempting design is to write a method that reads one file and returns an array, then call it once for each input file. That approach creates two separate arrays, which must then be combined. For enormous lists, this wastes storage.
A single method could instead read both files into one array. However, it must also preserve the boundary between the original sorted data and the unsorted data. The sorting algorithm needs the size of the first list, so the method must somehow provide both the array and that size. Returning both values requires an additional design mechanism.
One efficient design is:
The main method reads the counts from both files.
It passes both file scanners and both counts to a
readFilesmethod.readFilesallocates one array of the combined size and fills it from both files.The sorting method receives the combined array and the original sorted-list size.
The output method writes the unique values to a file.
This design is not necessarily the most elegant, but it keeps the data in one array and makes the information needed by the sorting algorithm available.
Reading both files into one array
The combined array has a capacity equal to the sum of the two input counts. A single index is used across both file-reading loops:
The first loop reads the sorted file into the beginning of the array.
The same index continues through the second loop to read the unsorted file into the remaining positions.
The completed array is returned.
Keeping the index outside both loops is important. If the second loop restarted at zero, it would overwrite the first list. If it started at the wrong position, the two sections would not be stored correctly.
The method can also verify that the expected number of lines was read. Such checks help distinguish an algorithm error from a problem in a damaged or incorrectly formatted input file.
Writing the output file
A file-writing method takes an output filename and the data array. A PrintWriter is appropriate because it writes text; a Scanner is used for reading, not output.
The method writes:
The number of distinct values that will appear in the file.
Each distinct value on its own line.
A closing operation for the output file.
Files should be closed when processing is finished so that output is properly completed and system resources are released.
Implementing the adapted selection sort
The adapted algorithm uses an outer loop to visit every array position. At each position, it identifies the smallest value that belongs there.
For each position:
Set the current position as the initial minimum.
Decide where the search should begin:
If the current position is in the original sorted portion, begin searching at the first unsorted position.
If the current position is already in the unsorted portion, begin at the next array position.
Examine the relevant later values and update the minimum position whenever a smaller value is found.
Swap the minimum value into the current position if it is not already there.
A temporary variable is used for a swap so that neither value is lost.
Comparing strings
Strings cannot be compared with numeric operators such as “less than.” In Java, compareTo determines lexicographic order:
A negative result means the receiver is lexicographically smaller.
A result of zero means the strings are equal in ordering.
A positive result means the receiver is lexicographically greater.
For this algorithm, a negative compareTo result indicates that a newly examined value should become the current minimum.
The Arrays utility class provides array operations such as sorting and binary search, but a general swap operation is not supplied in the same way for arrays. The algorithm therefore uses a temporary string variable to perform its swap.
Because the adapted algorithm’s two search phases can initially look unusual, comments explaining the boundary between the sorted and unsorted portions make the code easier to review and maintain.
Removing duplicates while writing
After sorting, duplicate values are adjacent. The output method can therefore identify unique values by comparing each value with the one immediately before it.
The first value is handled separately because it has no predecessor. If the array is nonempty, that value is written before the loop. The loop then begins with the next position and writes a value only when it differs from the previous value.
String contents must be compared with equals, not with reference comparison. The first array position also needs special handling: attempting to compare it with the value at index one before the array has a preceding element would access an invalid position.
The number written at the beginning of the output file must account for duplicates. One way to compute it is to count adjacent repetitions and subtract that count from the full array length. For a run of r equal values, there are r−1 excess copies, so counting equal adjacent pairs gives the number of copies removed.
For example, if the two input lists contain 10 and 3 values, the combined array contains 13 values. If the lists share one duplicate value, the output contains 12 distinct values. The output count must therefore be 12, not 13.
A common logic error is to count unequal adjacent values instead of equal ones. Another is to remove duplicates from the written lines but leave the original array length in the file header. Both the filtering condition and the output count must follow the same duplicate policy.
Testing and verification
Program testing should proceed in stages so that errors can be localized:
Test that the files are found and their counts are read.
Test that both lists are placed into the combined array in the correct order.
Write the combined data before sorting to confirm that all input values were read.
Test sorting separately by checking that the final array is ordered.
Test duplicate removal and confirm that the file’s count matches the number of lines of data.
Test boundary cases such as empty lists, one-element lists, and repeated values.
A program that runs without crashing has not necessarily produced correct results. The output must be inspected and compared with expected counts and ordering. In particular, a mismatch between the file’s declared count and its actual data lines can reveal a duplicate-counting or output-format error.
Why algorithm details matter
Library methods are useful, but understanding the algorithms behind them expands the set of techniques available for solving new problems. If a programmer knows only how to call a general sorting method, the easiest solution may be to sort all values from scratch, even when part of the data is already ordered.
Understanding algorithms as building blocks makes it possible to adapt existing methods, recognize useful properties of the data, and evaluate trade-offs in time, storage, and implementation complexity. This knowledge helps determine when a library method is appropriate and when a specialized approach can better meet the program’s constraints.

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