5 - 1 - sorting introduction (14-43)

Upload: aadheeshwar-vijayakumar

Post on 03-Jun-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 5 - 1 - Sorting Introduction (14-43)

    1/5

    Okay, what are the rules that we're goingto follow? Well, let's start with lookingat a typical basic sorting problem. Say,university has student records and forevery student there is a certain amount ofinformation. Maybe there's a class number,there is a grade, there's a phone numbermaybe an address so we refer to an itemand it has a record or the informationthat we're going to sort. But inparticular, there's a piece of a recordcalled a key and what we want to do is putthe records into order according to thekey. That's the sort problem. Re-arrangean array of n items into ascending orderaccording to a defined key which is partof the item. Now, our goal is to be ableto sort any type of data so let's look ata couple of client programs. First exampleis to just sort some random real numbersinto ascending order. So, here's a clientthat calls our insertion sort method andall it does is read numbers from standard

    input than into an array a then callsinsertion sort and then prints them out.And you can see on the right that thenumbers are printed out in sorted order.This seems like an artificial kind ofinput but actually we'll look at anapplication even in this lecture. And thenthere are many applications where randominputs are fine model. Here's maybe a morefamiliar sort client that sort strings.And in this case it reads the strings froma file using our readStrings() method inour In class that which takes a file as

    argument. So we take the file name as thefirst command line argument, read in arrayof string from that file separated byblanks, call an Insertion.sort() method again. So,Insertion.sort is a method that takes anarray a as its parameter and it, it's thefirst argument and it rearranges thestrings in that array to be in sortedorder. So in this case words, wordsthree.text has the certain number of threeletter words and this client program willresult in those three letter words beingrearranged into alphabetical order.

    Here's another client that we could useour sort program for, if we achieved thegoal of sorting any type of data. In thisone, we're going to sort file, file's namein a given directory. So again we use theFile class from Java and we use, we go anduse the listFiles() method from that classto get an array that contains all the filenames in the given directory. That's anarray with file names in it and Insertion.sort()

  • 8/12/2019 5 - 1 - Sorting Introduction (14-43)

    2/5

    takes that array as its firstargument and again sorts them and then wego ahead and use as, go through them oneby one and print them and they come out inorder of file name. So that's threedifferent clients, three completelydifferent types of data. And the firstrule of the game that we have to thinkabout is, how can we make it so that wecan implement one sort program that can beused by these three different clients toimplement three different types of data.In the way that, that happens is amechanism known as a callback. So, that'sour basic question, how can sort, now, howto compare data of all those differenttypes without being given any informationabout the type of an item's key? And theanswer is that what is we set up amechanism known as a callback or referenceto executable code where the client, bypassing an array of objects to the sortfunction. In Java, there's an implicitmechanism that says that any such array of

    object is going to have the compareTo()method, then the sort function calls backthe compareTo() method associated with theobjects in the array when it ever needs,whenever it needs to compare two items.There's a lot of different ways toimplement callbacks and that'sprogramming language specific. Differentlanguages have different mechanisms. It'sall about the idea of passing functions asarguments to other functions which is thepair and gets into functional programmingand thinking all the way back to Turing and

    Church. For Java, because of the desireto check types at compile time, the use ofspecific method called an interface andthen, we'll look at the details of how toimplement callbacks with the Javainterfaces now. It's a little bit ofprogramming language detailed but it's,it's really worthwhile because it allowsus to use the sorts that we developed forany type of data in a type safe manner. Sowe already looked at some clients. This isthe example of the client program thatsorts the files in a given directory by

    file name. So it just calls our sort()method with a, an array some type ofobject as first argument. Now, built in toJava is the so-called the Comparableinterface and all the Comparable interfaceis the specification that a type, datatype that implements Comparable will havea compareTo() method. And it's generic andwill be compared to against a certain typeof item. Now when we implement objects

  • 8/12/2019 5 - 1 - Sorting Introduction (14-43)

    3/5

    that are to be sorted we'll implement theComparable method. That's up in the topclass file, implements comparable file.And since sorting is an operation that'sused in so many situations, many of thestandard Java types that you would expectto involve sorts will implementComparable. And all that means is that,that data type has an instance method thatwill implement the compareTo() method.It'll compare this object against theobject given as argument and depending onsome complicated tests, it'll return -1,meaning less, +1, meaning greater or0, meaning equal. Now, that compareTo()method is really all that the sortimplementation needs. First it says that,that it's going to take as argument anarray of type Comparable. So that means,the objects in the array are going toimplement the Comparable interface or thatit will have a compareTo() method. And thenthe sort code can just use that compareTo()method, invoked in a sense of the

    object like an entry in the array and asargument and another instance in theobject like another entry in the array totest whether the first is less than thesecond as in this example. The key pointis that the sort implementation has nodependence on the type of data that'shandled by the Comparable interface and adifferent Comparable array will be sortedin the same way though eventually, becauseof the interface mechanism, they call backto the actual compareTo() code that goeswith a type of object being sorted. Now

    there's a few rules and there's naturalrules but they're worth talking about andpaying attention to that the compareTo()method has to implement in the so called atotal order. In all that saying is reallythat it must be possible to put items inorder in a sort. So there's threeproperties. First one says that if v isless than or equal to w and w is less thanor equal to v then the only way for thatto be true is if they're equal and thenthere's transitivity. If v less than w, wis less than x, then v must be less than

    or equal to x. In totality, is that eitherv is less than or equal to w or w is lessthan equal to v or both they are equal.And there's plenty of natural total ordersin the types of data that we normally wantto consider for sort keys. Like theintegers or natural numbers or realnumbers or alphabetical order for strings,chronological order for dates or times andso forth. The cartoon on the right shows

  • 8/12/2019 5 - 1 - Sorting Introduction (14-43)

    4/5

    that not all orders are necessarily totalorders. So, rock, paper, scissors is intransitive.If you know that v is lessthat w, w is less than v, you don't knowthat v is less than or equal to v. I'msorry, v is less than w, w less than equalto x that you don't necessarily know thatv is less than or equal to x. Alright. Sothe Comparable API then, by convention inJava we always need to implement compareTo()such that v that compared to w is atotal order. And also by convention, itreturns a negative integer for its lesszero if it's equal positive its greater.If this object is greater than the objectgiven as argument. If the types areincompatible or if either one is nullcompareTo() should throw an exception.Now, again, many of Java's standard typesfor numbers and dates and files and soforth implement compareTo() by convention.Now if we're going to implement our owntype then we have to go ahead andimplement the Comparable interface

    according to these rules. And usuallythat's fairly straightforward. So here'san example. It's a simplified version ofthe Date class that's implemented withinJava just to show the idea of implementingComparable. So, after the classdeclaration, we write implementsComparable and then we fill in the genericwith the same type because we're onlygoing to compare dates to other dates. Inthis implementation, the Date class hasthree instance variables. The month, theday and the year and the constructor

    fills those from the arguments as you cansee. So now, if you want to compare twodifferent dates then the first thing to dois to check if this year is less than thatyear, over that is the year given, thedate given in the argument. If that's truethen it's less return -1 and if it's,the year is greater, return +1.Otherwise, the year, years must be equalso we have to look at the months to do thecompare and so forth down to do the days.Only if they're all equal that we returnzero. So, that's an example of an

    implementation of Comparable byimplementing the compareTo() method to putdates in order as you might expect. So theJava language helps us with thisComparable mechanism so that we can sortdata of any type. When we continue toimplement sorting algorithms, we'reactually even in a hide that beneath ourown implementations. So, that are sortingalgorithms actually their actual code can

  • 8/12/2019 5 - 1 - Sorting Introduction (14-43)

    5/5

    be used to implement sorting in many otherlanguages. The way we do that is to takethe two primary operations, compares andexchangers that were that were, were usedto refer the data and encapsulate themjust the static methods. So, we're goingto use a method less() that takes twoComparable objects as arguments and itjust returns, v.compareTo(w) less thanzero. And then the other thing that we dowhen we sort items that are in an array isto, to swap or exchange of the item at agiven index i with the one at a givenindex j. And that's every programmer'sfirst introduction to assignmentstatements. We save a[i] in a variable swap,put a[j] in a[i], and then put swap backin a[j]. So now our sort methods to referthe data will just use this two staticmethods. And there's a good reason forthat. Here's an example. Suppose we wantto test if an array is sorted. So this isa static method that is supposed to returntrue if the array is sorted and false if it's

    not. And all it does is just go throughthe array from the one to the length ofthe array and test if each item is lessthan the one before. If you have an itemthat's less than one before then it's notsorted you return false. If you get allthe way through the array without thathappening, then you say the array is true.That's pretty simple code, the questionis, if you have a sorting algorithm thatpasses that test, are you sure that itcorrectly sorted the array? Well theanswer to that question is, yes if, yes if

    you used only the less() and exchange()methods to implement, to refer the databecause then you know because you used theexchange() method that the data in the arrayafter the sort is the same data as was inthe array before the sort, sort. If youhave a sort method that can store anyvalues in an array, it could, for example,store zeros in every array entry thatmethod would pass this test, but it didn'treally correctly sort the array becauseoverwrote all the values. So, we use less()and exchange() to be sure that we can test

    that our, our methods work with the methodlike this.