Sorting Partially Sorted Data
Transcript
>>Dr. Deborah Trytten: Let's continue our study of sorting by looking at partially sorted data. Here's the problem statement. You work for TextBooksAreUs, a company that sells college textbooks. TextBooksAreUs has just purchased a small company, LittleTexts, that also sells college textbooks. You've been asked to merge two lists of email addresses. TextBooksAreUs's is sorted by email address, but LittleTexts's list is sorted by domain. The final list is supposed to be sorted by email address. Now the first thing we want to do is consider whether this problem can be abstracted. So for example, does this problem really have anything to do with email addresses or could we write a general program that merges a sorted and unsorted set of data? It would be different if we needed to sort by domain name because then the fact that they're email addresses really matters. So you want to look for opportunities
to make your program as general as possible when you're writing it. So let's select our test data. We'll call the larger sorted data set sortedData, so I've created a little table to show some of it. We'll call the smaller unsorted data unsortedData, and of course the results should be the two sets merged together and in sorted order. Now before we go too far, we might want to think a little more. It is virtually certain that these lists are going to contain duplicate values because people who buy stuff on the Internet can buy a lot of stuff on the Internet. So we've got to come up with some ideas on how we're going to deal with that. One possibility would be to remove them from unsortedData by performing a binary search on sortedData, and that's certainly a legitimate way that could be pursued. So we could use arrays dot binary search for this. The arrays class is
similar to the collections class, only it has utilities for arrays. The other thing we could do is just go ahead and sort and then remove the duplicates when we're writing the file. So we need to select a strategy here. Now binary search is much cheaper than linear search, but it still takes time. This is especially true because sorted data is large. So when you have large data sets, you need to be much more careful about wasting time, so that's probably not a good choice. Now removing duplicates when you're writing the file is easy, so that would be a great choice. The thing is this decision might be wrong if there are lots of duplicates. So maybe all of the email addresses are duplicates, for example. In that case we probably have made the wrong choice, so this brings up an important point. We need a better way to make these comparisons. Now we're not going to
develop it this semester. The class that it's developed in is one called Data Structures, a class that you'll certainly take if you continue to study computer programming. Now we need to improve our test data. Since we know we're going to have duplicates around, we want to include that in the test data. So what I've done here is added to the unsortedData j. So that way we have a value that's in both the sorted and unsorted data, and we know the result in the array should then have two j's in it but the file should only have one j. We need to think about the format of the files. Here's a format that makes a lot of sense. First you'll have the number of email addresses, and then you'll have the email addresses one to a line. This is a very common way to write files, and file formats are something that are very important to pay attention to. The advantage of this particular choice is because
we know the number of email addresses. That makes it possible to directly construct the array instead of having to read through the file once to figure out how much data is in it, and then construct the array and read the data again. So that's one of the reasons that this format is rather common. Now there's some boundary cases we need to consider. We might consider what happens if there's no sorted data. Now in this case the file would just contain zero. It wouldn't be an empty file because it was just an empty file that wouldn't follow our file formatting specifications. We might consider what happens with no unsorted data. What if only one element is in sorted or only one in unsorted and maybe only one element in both? So these are boundary cases as always that we should be testing. Now there's a very easy algorithm to do this. That's put all the data in a single array
and call arrays dot sort. What could be better than that? Well, that's really not the best thing to do. The thing is these lists are likely to be enormous, and you're not taking advantage of the fact that the existing data is already sorted. Particularly when you have the large data set, you want to look for ways to do these things more efficiently. On the other hand, this would be a good choice if the main constraint is the time to write the program. This would certainly be the shortest way to write the program, and sometimes that is the case. Let's consider another possibility. How could we adapt the sorting algorithms that we already know to this new circumstance? Well, I have basically three ideas to work from. The first one is to adapt selection sort, the second one is to adapt insertion sort, and the third one is what's called a two finger merge. Now this is actually part of a different sorting
algorithm that we haven't covered yet, and we'll talk about why it may not be the best way to do things, and I'll even explain what it means. Let's think about how we would adapt selection sort. Well, we know that selection sort first looks for the smallest element so that could be the first element in sortedData or it could be any element in unsortedData. Then we need to think about what's going to happen when swaps occur. Now when I first started thinking about this, I thought it was going to be a real mess. But I needed to draw a picture of it to see that there's a pretty good way to do this, so let's take a look at the algorithm. Now I've put this in a table and we'll go through the table one line at a time to talk about how the algorithm would work before we try to program it. As always, you must understand the details of how things work before you start writing code.
So here is the table that shows selection sort. We would start with value a. A would be the smallest, and we would compare it then to u, j, and k. Well, since a is the smallest, it stays in its position. The same thing would be true of everything all the way up to j. The first time things are going to change is when we hit m because we're going to compare m to u, j, and k and find out that j is smaller. So now a swap needs to occur. So we swap j here and m there. Next we need to go to p. We can see that p is smaller than k, and so
k and p get swapped, and this process continues all the way through. Now when we get right down to the end, you'll notice the last two are already in the correct position, so no swaps occur. So essentially once we start swapping, we're going to be doing a lot of swapping. So let's make some observations. Once the first swap is made, the sorted data starts getting mixed with the unsorted data. But are we losing the value of having the data sorted? Let's go back and take another look at that table. So here's the table again. Notice, for example, when we swap that m, we're putting it into a place of values that are still bigger than any place we are in the algorithm. In other words, we're not really losing the value of having that data sorted. We're just moving positions around. Now this could be complex to code. We're going to have two phases of the algorithm, one where it's
stepping through the sorted data, and then a second one where it's stepping through the unsorted data. That second one is going to look very much like our original selection sort. So that might be complicated, and complexity is something you definitely want to worry about. It's much harder to write complex algorithms correctly. Now let's think about what would happen if we adapted insertion sort. Now remember with insertion sort, you start with a group of sorted data and then you add unsorted elements to it one at a time. So when we find our u in the insertion sort unsorted data, notice it's already bigger than t, and so it's in its correct position already. Well, that was kind of cool. Now for j we set j to the side, and we notice that u is bigger than j, and t is bigger than j, and r is bigger than j, and q is bigger than j, and p is bigger than
j, and m is bigger than j, and finally we find that other j, and that's when we swap the j into that position that we set aside. Now notice we're not done yet. We would do that exact same thing for k, and it would look pretty much the same. So there's a lot of swapping going on here. Remember that the size in the data elements here. You know, I'm showing ten and three elements. These are likely to be millions of elements, not ten and three. Some observations on that one: this is essentially starting insertion sort at a midway point, and that means that virtually no code would need to change. It's just one starting condition on a loop, so that's a big advantage. We're also never losing the value of any of our unsorted data, but then again we weren't losing it in the other algorithm either. And it looks like we could get into a lot of swapping, and so that's definitely a problem because swapping is expensive.
Now let's look at a third choice. This choice is called two finger merge. The idea behind it is you should sort the smaller array too. Now that we could use arrays dot sort for, and then merge the two arrays together. So what you'd do is choose the smallest value from the end of either array and put that in the result array. Let me show you a picture. So we've got our first values that are sorted in the blue on the left, and in the orange we had u, j, k. So we call the sorting algorithm and get them sorted into j, k, u, and then we start making these comparisons. So we compare a to j. Now notice we don't need to compare any k and u now because we know j is the smallest value in the orange set, and a gets moved in. Then we compare b to j, and b gets moved in. Then we compare f to j, and f gets moved
in, g to j, g gets moved in, j to j, whichever it doesn't really matter. Now you're comparing m and j, so that means that the j from the second set is going to have to move then. The next thing that will move in is k from the second set because k is smaller than m, and then m will go back. The most important observation here is that when you're approaching merging, this requires a second array to store the results. That's a problem because it doubles the amount of storage. Remember these are enormous arrays in all probability, so you
don't want to double the amount of storage. It might mean that the program doesn't work at all, so that's really a deal breaker. So now we've got to make a decision. Selection sort and insertion sort won out because they required only one array instead of two arrays, and choosing between them is kind of a toss-up. It looks like selection sort may end up being a little more efficient, but it also might be harder to implement, whereas insertion sort is easier to implement because it's a minor change to an existing algorithm. But in this particular case efficiency is what's driving it because remember the reason we didn't just do this arrays dot sort at the start was because we wanted to be more efficient, and so that argues for selection sort. And once again, we clearly need some better tools for comparisons, and computer scientists have them. We just don't have them yet. The next challenge we have is designing the methods. Now you might think it'd be nice
to do string square brackets read file and then give the file name. We could call that method twice. That would be good. That would be reusing code. But we've got a little problem here, and that's that we would then have to store the data twice because we would read the first sorted data into one array and then the second unsorted data into another and then have to combine them together. Oops, that's doubling the storage space. Remember we're trying to be efficient in this particular program, and doubling the storage space is not efficient. So we need to consider a different design. We could write one method that reads both files and it would get the sorted filename and the unsorted file name and it would return a string array. Well, that sounds good, but we've got a return value problem. We certainly need to return the array. I mean, that's the whole purpose of reading the files, right.
But you also need to return the size of the first file because you have to know where that division is. Now you could say, "Well, I could write a method that goes and finds it." And I agree, you could do that. But once again, that's getting expensive, so this signature really doesn't work. Now this is the solution I came up with, and I've got to say I think it's kind of an ugly solution, but when you're trying to be efficient sometimes you do things that are ugly. And that's to read the file sizes in the main method and read the data in another method. That way we have the file sizes when we need them for calling other methods. This is what the signature would look like. We would have read files, and it would take a scanner from the sortedFile, a scanner from the unsortedFile, and then pass in the number of data in each file, and this would return a string array. I can't tell you that I love this design because
I don't, but on the other hand it does accomplish the basic goals, and it does it efficiently. There's some other methods we're going to need. We're certainly going to have to write a method to save to a file, so it will take an output file name in the data array. Remember we're going to have to deal with duplicates in that method, and we're going to have to write our sort merged data, so expect that to be sort of the interesting part of the algorithm to write. So let's go to Eclipse and start writing these methods. Now I've written the main method already. So notice I created a scanner to interact with the keyboard so we could talk to the user. Then we've got these three file names, and we get those file names from the user. Then I create a scanner to read the sorted file and read in the size first because remember that's the first thing written in the file. The other thing I'm doing here is
reading in the next line. You know, that's to remove that end of line character that we always have so much trouble with. We do the same thing for the unsorted file. Here we're calling the read file methods. So notice it's taking the sorted file, the unsorted file, the sorted size, and the unsorted size. The next thing I'm doing is closing both of those files. Now that's going to turn out to be really important. You always want to remember to close files. Then we're going to sort the merged data, which will take the data array and the sorted size, and lastly save things to a file. So those are the way the methods are going to fit together. Now let's go and write the little methods. So we could write any one first, but I think it probably makes sense to write the read file method first, so sort of stepping through things in the order they would be implemented. This is also good for testing. So we know
that we're going to need to create a string array of sorted size plus unsorted size. Notice I constructed the references to the strings here, and we know we're going to have to return it. Now the challenge here is we're reading two files into one array, so we can't just use our regular for loops. We're going to need to start with an index, which is zero, and then we'll have one for loop that reads in the sorted data first and then a second for loop that reads in the unsorted data. The thing that's a little different here is we need to use this index in both of those for loops. So we can't declare it in the first for loop because if I put int index equals zero here on line 87 instead of on line 86, what's going to happen is that that will be part of that for loop, and then we'll have to worry about where to start the second one. Since there's no initialization, what we do
there is put just a semicolon. Now another option here would be to write this is as a while loop, but frankly I like for loops better than while loops, so we're going to do it this way. So we're going to say index is less than sorted size and then index plus plus index. So result of index is going to equal sorted file dot next line. So that's all it takes to read in the first file. Now we need to read in the second file. Again, we're not going to create a variable for index.
We're going to use the one we already have. Now that index is going to have to stop. It's sorted size plus unsorted size, and then of course we'll increment the index again. So result of index equals unsorted file dot next line, and then we return the result. Now one thing we might want to worry about here is that files do sometimes get corrupted. That might mean that they might be missing data or have extra data or something like that, and so we could put another little test here, and that's and sorted file dot has next line.
That's kind of a nice way to do things, but remember that we're going to have to make sure that the user is warned if the files are corrupted. Because if the files have been corrupted, this program isn't going to work correctly, not because our program isn't correct, but because somebody else's wasn't. And so we definitely want to be careful about doing things like this. So this could be kind of nice. The question is: how are we going to flag to the user that something's gone wrong? So let's say if index is not equal to sorted size. We could print out an error message, and we can do the same thing on the second
for loop. Now we're probably going to want to put some parentheses around not because they're necessary—they actually are not—but just because it makes the code a little bit easier to read. Then we'll copy this and do a test here before we return. Of course it's not index not equal to sorted size. It's index not equal to sorted size plus unsorted size.
So now we've been appropriately cautious. Now I've created some data. Let me show you what it looks like. Here's our sorted data. There are ten elements in it. It's the test data we developed in the PowerPoint. Here's our unsorted data. That final data dot text is the one we're going to be overwriting eventually. So let's run our program. So this is sorted data dot text, unsorted data dot text, and
we'll call it final data dot text. Now nothing happened, so we really don't know that our code is working correctly. On the other hand, it also didn't break. So it seems like it found the files okay. Probably everything's all right, and we didn't get any error messages. So we don't really know, but we're kind of hoping for the best. I think probably the next thing we might want to do is to write the save to file method because really that's going to be important for us testing. So we could save it to the file without the data being sorted, and check and make sure that our method is working correctly. So this is a pretty simple method. Notice we're taking a file name, so we'll need a scanner that comes from a file with a given file name. You'll notice I already have this method throwing
a file not found exception, so we don't have to worry about that part. So now we will write out...oh, silly me. Scanner is for input. We're doing output. So we need a print writer. Okay, that looks a little bit better. So now we're going to do file dot print line of data dot length, the number of elements that were in the array, and then we're going to step through the array one element at a time and write out the file. So we'll do file dot print line data of i. And of course at the end of the method we're going to do file dot close.
Okay, so that's how you save to a file, pretty simple code. Let's run again. Okay, so now we can look at final data and see if it contains the right things. Now we're not expecting it to be sorted, and you'll notice that it isn't sorted, but it does have the right stuff in it. It has fourteen lines, which is good because we have thirteen data elements. So it looks like that part is working just fine. Now the next thing we need to do is to wrestle this sorting algorithm. So we're going to have to really think through how we're going
to proceed. So the first thing we're going to do is we're going to have to step through the data one element at a time. This is selection sort, remember. So for int index is zero. So we know eventually we're going to have to step through every single element in the array. So that's definitely the outside for loop we want. Now we need to find the next minimum value and put it in the proper position because that's what selection sort does. So let's put some comments in here. Okay, well, if the index is less than the sorted size,
our minimum index, which by the way we need to declare, would be the current index. Remember that before the sorted size we're always comparing just the next element in the array with all the ones in the unsorted category. Now let's think about what would happen if we're in the unsorted category. Is our first minimum index going to be index? Well, I think it is. So maybe we don't need this test at all. Whether we're in the sorted or unsorted category, our first minimum is going to start at index. Here's the second for loop. So we're going
to start at—well, we've got two possibilities. If we're still in the sorted part of the data, we are going to start at the unsorted part of the data. If we're in the unsorted part of the data, we're just going to start at the next index. So we have to think about how to say that. Let's do it in an if statement and create next outside of this loop to keep things a little bit cleaner. If the index is less than the sorted size, next equals sorted size. So we're searching the unsorted data. Otherwise next equals index plus one.
So we don't want to make the comparison to the current index because we've already done that. So for now we've got next created, so we don't have to initialize that. Next is going to have to be less than data dot length, and we're going through next one at a time. If data of next is less than data of min index, then min index equals next.
So let's put some comments in here. Notice this is a little more involved algorithm than some of the ones we've written, so that's when writing a few extra comments really pays off. If we're still in the unsorted—whoops—still in the sorted data start at the next element in the array. If we're in the unsorted data, no, we start here at the first element in the unsorted data. If we're at unsorted data, start at the next element. Okay, so you really
while you're thinking about these things want to put in as many comments as possible because this is the kind of code when people look at it that they're going to think it's not right even when it is. So let's see what Eclipse is unhappy about here. Oh, now Eclipse has a point. Somehow I managed to forget that we're dealing with strings, so we can't use less than. We have to use compare to. Now remember compare to returns a negative number when the implicit variable, that is, when data dot next is less than data dot min index.
So when this is less than zero, it's when want to do that. Now the last thing we want to do is swap the data. So if min index is not equal to index, remember if those two are equal, we don't want to do a swap so we'll have a string, which we call temp. You've seen swaps all over the place, so this is easy. So this will be data of min index, then data of min index equals data of index, and data of index equals temp. If you're thinking
to yourself, "Wait a minute. Didn't we have a swap method?" we did. The problem is it's in the collections class. The arrays class didn't have a parallel method, and believe me I went and looked for it. Okay, so we kind of hope maybe we've got our program done. Wow. Notice that although this algorithm sounded like it was going to be complicated to write, it really isn't that bad. It's just a couple of nested for loops. So our console went to a strange place, but that's fine. We can work with that. Unsorted data dot text, and we're going to end up with
final data dot text. Well, nothing broke. That was exciting. So let's look at final data. Now notice I'm getting an error message here from Eclipse. It says, "This file has been changed on the file system. Do you want to replace the editor cotents with these changes?" So what Eclipse is saying here is, "Wait a minute. I didn't change this file, and it has different stuff in it," so yes, we do. We know we changed that file. So when we take a look at the data, we see something cool, and that is that we've actually gotten our data sorted correctly. That's pretty amazing for running this program once because this is kind of a complicated algorithm. But we also see that we made a mistake. That's the two j's are showing up in the file. So in our excitement to get the code written, we forgot to deal with the duplicate problem. So let's go back and deal with that problem.
Now that's going to be in the file writing. So that was that nice little short method that we wrote. So here's the problem. We've got to worry about when to get the data out. If data of i is not equal to data of i minus one—We've already been caught once with string problems. So we know we're working with strings, and remember when you work with strings, you have to use the equals method and of course an exclamation point in front.
So that's when you want to print this out. Now let's think a little bit about what's going to happen the first time through the loop. So when i is zero, it's going to try to compare data of zero and data of negative one, so that isn't going to work. We're going to have to say here i is greater than zero, and those two are not equal to each other. Now the thing about this remember that that double ampersand does something called shortcutting. So if it doesn't find that array is greater than zero, then it's not going to try to calculate this part. The other thing we might want to worry about is where do we print out data of zero? Hmm. Well, one possibility would be to do it before the loop, and that's okay
as long as you put a conditional statement in there so that if the final file has zero length, you don't try to print something that isn't there. The other thing we could do if these two things aren't true is maybe put in an else statement. Now we have to be a little careful with that too, so let's handle the zero case before. If data dot length is not equal to zero, then we'll do file dot print line data of zero. That's better than
putting it in the loop. The reason you don't want to put it in the loop is if you put it in the loop, the statement's going to be executed every time when it's just a special case we need to worry about right at the start. Now the other thing we could do here is even clean up the code a little bit better now. We don't need to start at zero anymore, and that means we don't have to test for zero. So that actually ended up making the code quite a bit cleaner. Okay, so let's run it and see what happens. So sorted data dot text, unsorted data dot text, and final data dot text. Everything seemed to run just fine. We go and look at
it. We're getting the same error message as always, but now we have a problem. And this problem is subtle, so you might miss it if you weren't really paying attention. Notice that I say we have thirteen elements in the file, but we really only have twelve. We forgot to handle the duplicate case when we were printing out the file, so we've got another little problem here. So we can't just go and print out the data dot length. We're going to have to count the duplicates first. We've got some pretty good code for finding duplicates.
So let's use that code. But instead of printing out to the file here, what we're going to do is increment duplicates. So then when we print out the file, it'll be data length minus duplicates. Okay, let's see if our program runs now. Entering the file names again. Nothing
broke. That's always nice, and let's look at our final data. Two? That's kind of weird. We must've done something strange. Ah, we forgot to change our logic. We're counting duplicates, not things that aren't duplicates, so that shouldn't have been a not sign in there. It should've been just when they're equal that they're duplicates. So here we go again, and now we have twelve values, the correct number. And in fact, this code is
going to pass all the other tests if we were to run them. Let's talk about algorithms a little bit. When we were looking at insertion sort and selection sort, you might've wondered why you need to know the details of the algorithms when they're methods in the API. Well, the reason is that algorithms are building blocks for programs and knowing the details of the algorithm gives you a better set of blocks to play with. For example, if we had to approach this problem and we didn't know selection sort or insertion sort, the only thing we could do is call the arrays dot sort method, and that's not the most efficient way to do it. And that's why you need to know the details of algorithms, even when you don't necessarily implement them every day and even when it's good to call things from the API. So keep programming!

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