Would this sorting algorithm work?

I'm writing a sorting algorithm for a class that implements the Comparable interface. The class (called Memo) has a field, 'entryDate' of type 'Date', which itself has int fields for day, month, and year. I want to have the class sorted by date, earliest to latest, and then (for entries on the same day) by 'priority' (a field of type int; can be 1, 2 or 3).
The one I've written seems to work based on a few tests, but I just want to make sure it will work all the time:
(btw, i have to use the 'getEntryDate()' method because entryDate is a private field in the Memo class' superclass.
public int compareTo(Memo memo)
int comparison = getEntryDate().getYear() - memo.getEntryDate().getYear();
if(comparison != 0) {
return comparison;
comparison = getEntryDate().getMonth() - memo.getEntryDate().getMonth();
if(comparison != 0) {
return comparison;
comparison = getEntryDate().getDay() - memo.getEntryDate().getDay();
if(comparison != 0) {
return comparison;
return priority - memo.priority;
}

Generally when you simply subtract one int value from another in the compareTo() method, you'll have to take care that you don't run into an overflow situation (because comparing Integer.MIN_VALUE and (Integer.MIN_VALUE-1) would result in unpleasant surprises otherwise). But in your case you can probably safely assume that all your values are well within the safe range for int.
Also: If you have the chance to modify the Date chance I'd simply make the Date implement Comparable<Date> and delegate that comparison to the Date class.
Also: are two Memos at the same date with the same priority considered equal? Don't they have any other fields? It's important that objects that are not equals (i.e. a.equals(b) returns false) don't compare to be the same (i.e. a.compareTo(b) should only return 0 iff a.equals(b) returns true). Otherwise you might run into situations where objects are silently dropped because some Collection classes consider them to be equal (SortedSet implementations are tricky here).

Similar Messages

  • [SOLVED] What is this sorting algorithm? (or a new one?)

    Hello everyone!
    Just before starting, i apologize for my grammar mistakes.
    I found a new sorting algorithm but i'm not sure if i really found it. There are too many sorting algorithms and mine is a really simple one; so, i belive that it can be found years ago.
    I searched popular sorting algorithms, but none of the them is the answer.
    Here is algorithm:
    * Search the numbers between brackets
    [24 12 12 55 64 18 32 31]
    * Find smallest one
    [24 12 12 55 64 18 32 31]
    ^S
    * Swap the first item between brackets with smallest one
    [12 12 24 55 64 18 32 31]
    * Find largest one
    [12 12 24 55 64 18 32 31]
    ^L
    * Swap the last item between brackets with largest one
    [12 12 24 55 31 18 32 64]
    * Move brackets by one.
    12[12 24 55 31 18 32]64
    * Continue from step one until the array is sorted
    /* rottsort
    Copyright (c) 2013 Bora M. Alper
    #include <stdio.h>
    void print_array (const int *array, const int length);
    int rottsort_swap (int *x, int *y);
    void rottsort (int *array, const int length);
    int rottsort_largest (const int *array, const int start, const int end);
    int rottsort_smallest (const int *array, const int start, const int end);
    void print_array (const int *array, const int length) {
    int i;
    for (i=0; i < length; ++i)
    printf ("%d ", array[i]);
    putchar ('\n');
    int main (void) {
    int array[] = {24, 12, 12, 55, 64, 18, 32, 31};
    print_array(array, 8);
    rottsort(array, 8);
    print_array(array, 8);
    return 0;
    int rottsort_swap (int *x, int *y) {
    const int temp = *x;
    *x = *y;
    *y = temp;
    void rottsort (int *array, const int length) {
    int i, largest_pos, smallest_pos;
    for (i=0; i < length/2; ++i) {
    largest_pos = rottsort_largest(array, i, length-1-i);
    rottsort_swap(&(array[largest_pos]), &(array[length-1-i]));
    smallest_pos = rottsort_smallest(array, i, length-1-i);
    rottsort_swap(&(array[smallest_pos]), &(array[i]));
    int rottsort_largest (const int *array, const int start, const int end) {
    int i, largest_pos = start;
    for (i=start; i <= end; ++i)
    if (array[i] >= array[largest_pos])
    largest_pos = i;
    return largest_pos;
    int rottsort_smallest (const int *array, const int start, const int end) {
    int i, smallest_pos = start;
    for (i=start; i <= end; ++i)
    if (array[i] <= array[smallest_pos])
    smallest_pos = i;
    return smallest_pos;
    P.S.: If this is a new sorting algorithm, i name it as "rottsort". :)
    Last edited by boraalper4 (2013-08-11 19:08:17)

    Trilby wrote:
    Because you already have two variables for largets and smallest, there is no reason to loop through the whole list twice to get each.  Loop through the list (or list subset) once, and in each loop check if the current item is smaller than smallest_pos or larger than largest_pos.
    This will increase efficiency by a factor of two.
    As written I believe it'd be less efficient than even a simple bubble sort.  With the above revision it may be comparable to a bubble sort.
    Thanks for quick answer and advice. :) I will try to do that. When i'm done, i will post the new code.
    Code is tested on codepad. (I edited the code on my phone so, sorry for formatting)
    /* rottsort
    Copyright (c) 2013 Bora M. Alper
    #include <stdio.h>
    void print_array (const int *array, const int length);
    int rottsort_swap (int *x, int *y);
    void rottsort (int *array, const int length);
    void rottsort_find (int *smallest_pos, int *largest_pos, const int *array, const int start, const int end);
    void print_array (const int *array, const int length) {
    int i;
    for (i=0; i < length; ++i)
    printf ("%d ", array[i]);
    putchar ('\n');
    int main (void) {
    int array[] = {24, 12, 12, 55, 64, 18, 32, 31};
    print_array(array, 8);
    rottsort(array, 8);
    print_array(array, 8);
    return 0;
    int rottsort_swap (int *x, int *y) {
    const int temp = *x;
    *x = *y;
    *y = temp;
    void rottsort (int *array, const int length) {
    int i, largest_pos, smallest_pos;
    for (i=0; i < length/2; ++i) {
    rottsort_find (&smallest_pos, &largest_pos, array, i, length-1-i);
    rottsort_swap(&(array[largest_pos]), &(array[length-1-i]));
    if (smallest_pos == length-1-i)
    smallest_pos = largest_pos;
    rottsort_swap(&(array[smallest_pos]), &(array[i]));
    void rottsort_find (int *smallest_pos, int *largest_pos, const int *array, const int start, const int end) {
    int i;
    *smallest_pos = start;
    *largest_pos = start;
    for (i=start; i <= end; ++i) {
    if (array[i] >= array[*largest_pos])
    *largest_pos = i;
    if (array[i] <= array[*smallest_pos])
    *smallest_pos = i;
    Last edited by boraalper4 (2013-08-11 15:21:48)

  • Would this storage card work in the Media Card slot of my W700?

    Hi,
    I'm interested in buying this Lexar 133x SDHC Card:
    http://lexarmedia.com/products/lexar-professional-133x-sdhc-card?category=213
    Basicallyl, I want to use it as another storage drive (as opposed to putting in my camera or other device).  So after I insert it, I want to be able to format it and use it as another storage area.  Would this card work?
    The reason I'm gravitating to that card is that is that I see in the specs that is minimum 20MB/sec read transfer rate and it does not take up one of my USB slots.
    However, even if it does work, would I be better off with their Echo ZX plug-and-forget it USB drive when they ship it?:
    http://lexarmedia.com/products/lexar-echo-zx-backup-drive-0?category=90
    If both work, which would be faster as a storage drive?
    Thanks.

    It is a SDHC card so it should work on the card reader of the W700.
    Regards,
    Jin Li
    May this year, be the year of 'DO'!
    I am a volunteer, and not a paid staff of Lenovo or Microsoft

  • Would this 1Tb drive work in my Mini?

    I found this...
    http://cgi.ebay.co.uk/ws/eBayISAPI.dll?ViewItem&item=150268266034&ssPageName=MER COSIVI_ROSI_PR4_PCN_BIX_Stores&refitem=160259809607&itemcount=4&refwidgetloc=closed_ view_item&refwidgettype=osi_widget&_trksid=p284.m185&trkparms=algo%3DSI%26its%3DI%252BIA%26itu%3DIA%252BUCI%26otn%3D4%26ps%3D42
    ...while looking for a new HD for my Mini. It looks better value than anything else I've seen - so I suspect I'm missing something.
    Anyone know if it would work?

    That is a 1 TB internal drive. 1-TB drives are going to be 3.5 inches.
    The Mini takes a 2.5 inch "notebook" drive.
    The 1 TB drive could work if you put it in the correct external enclosure (preferably one with Firewire and USB connections).
    But you can often find good deals on ready-to-go external drives, so look around.

  • Would this PHP Code Work?

    Hello there,
    I'm currently designing a website fot myself but need a page
    where people can send me feedback about the site or leave any
    questions. Now I've used some PHP to accomplish this but I shalln't
    be buying web hosting, etc until I've completely finished the site
    - therefore I am unable to test the the from to see if it works.
    The following is what I have done:
    1:) Created a HTML page with the following inserted into the
    body of the page:
    <form method="post" action="sendmail.php">
    Email: <input name="email" type="text" /><br />
    Message:<br />
    <textarea name="message" rows="15" cols="40">
    </textarea><br />
    <input type="submit" />
    </form>
    2:) I then created a PHP page with only the following code in
    the PHP file:
    <?
    $email = $_REQUEST['email'] ;
    $message = $_REQUEST['message'] ;
    mail( "[email protected]", "Feedback Form Results",
    $message, "From: $email" );
    header( "Location:
    http://www.example.com/thankyou.html"
    ?>
    I would be very grateful if somebody could perhaps test this
    or could tell me that it will indeed work - or as the case maybe,
    it won't.
    All the best,
    Kristopher (UK).

    Coxdabd wrote:
    > I would be very grateful if somebody could perhaps test
    this or could tell me
    > that it will indeed work - or as the case maybe, it
    won't.
    Yes, it will work. It will also turn your website into a
    wonderful spam
    relay. You should never trust user input without checking its
    content.
    Validating user input isn't something that can be covered in
    a simple
    forum post, but one thing that would make your script
    (marginally) safer
    is to remove "From: $email" from the mail() function. As
    currently
    scripted, it's a wide open security gap.
    David Powers, Adobe Community Expert
    Author, "The Essential Guide to Dreamweaver CS3" (friends of
    ED)
    Author, "PHP Solutions" (friends of ED)
    http://foundationphp.com/

  • Would this connection scenario work for sharing a printer?

    I work from home and my HP LaserJet is on it's last leg. My office computer is a an old Dell Optiplex - no wireless capabilities and my computer locks the PC down quite well so even installing a USB dongle would be out of the question. Hence my question.
    I was thinking of buying the Airport Extreme plugging my Samsung SCX-4500 into the Airport. The Airport would be plugged into my DSL router which the office PC is also. Would I be able to use the Samsung from the PC even though the PC is not wireless?
    I know my iMac would be able to get to it but I don't want to spend the money for the Airport as my HG2700-D has wireless built in.

    Would I be able to use the Samsung from the PC even though the PC is not wireless?
    Yes a scenario like that is possible as long as you configure the AirPort Extreme base station (AEBS) so that it acts as a bridge or the PC is connected to one of the AEBS's LAN ports.

  • Will this hard drive work with my macbook?

    I have a late 2006 Core Duo Macbook. I was wondering if I could use this hard drive with my macbook, it's a 7200 rpm 200 gig hard drive. Btw I mean internal not external. Does the macbook have a limit on how big of a hard drive you can use? Would this hard drive work at 7200 rpm in the macbook?
    http://www.newegg.com/Product/Product.aspx?Item=N82E16822145160

    Hi.
    The drive will work perfectly in your macbook. Two weeks ago i was also thinking about buying the Hitachi Travelstar 7k200.
    But afterwards i bought this one:
    http://www.newegg.com/Product/Product.aspx?Item=N82E16822136123
    The WD Scorpio 250GB. Off course it´s not as fast as the Travelstar. But for me three things we´re quiet nice about this harddrive: the noise (it doesn´t make anyone) and the price (got it for 150 euro) and it consumes way less power (means better battery life).
    http://www.storagereview.com/WD2500BEVS.sr?page=0%2C7
    BTW: It really doesn´t make any noise.
    So just in case you´re still unsure whether to buy the Hitachi or anything else. But if you want the fastest notebook HD you can get today, buy the Hitachi.
    Have a nice day and fun with your new HD!
    Message was edited by: dahack

  • Is there a way to address email (i.e. a word or some code) that would place that email in a specified inbox folder?  not using internal rule, rather the beginning of this sort happening as it comes in?

    is there a way to address email (i.e. a word or some code) that would place that email in a specified inbox folder?  not using internal rule, rather the beginning of this sort happening as it comes in?
    In other words
    I tell a friend if he is emailing me on a particular subject, is there something he can do at his end ([email protected]/research)
    like adding the word research at the end of my eamil address that would tell my inbox to place that in the inbox/research folder?
    If I have to use a rule on my end, then do I tell him to just place the word research in the subjct line and then I write a rule to place anything with the word research in the subject line in my inbox/research folder?
    will the subject line be required to only have the one word research to work, or will the rule look for any presense of that word in the subject line?
    thanks
    eric

    iCloud email supports 'plus' addressing. http://en.wikipedia.org/wiki/Email_address#Address_tags
    So your friend could just add '+research' to the username part of your email address, and you setup a rule at icloud.com to put all emails sent to that address into a particular folder.
    For example:
    [email protected]
    There's no way to do it without rules on the server though.

  • I need to sort very large Excel files and perform other operations.  How much faster would this be on a MacPro rather than my MacBook Pro i7, 2.6, 15R?

    I am a scientist and run my own business.  Money is tight.  I have some very large Excel files (~200MB) that I need to sort and perform logic operations on.  I currently use a MacBookPro (i7 core, 2.6GHz, 16GB 1600 MHz DDR3) and I am thinking about buying a multicore MacPro.  Some of the operations take half an hour to perform.  How much faster should I expect these operations to happen on a new MacPro?  Is there a significant speed advantage in the 6 core vs 4 core?  Practically speaking, what are the features I should look at and what is the speed bump I should expect if I go to 32GB or 64GB?  Related to this I am using a 32 bit version of Excel.  Is there a 64 bit spreadsheet that I can us on a Mac that has no limit on column and row size?

    Grant Bennet-Alder,
    It’s funny you mentioned using Activity Monitor.  I use it all the time to watch when a computation cycle is finished so I can avoid a crash.  I keep it up in the corner of my screen while I respond to email or work on a grant.  Typically the %CPU will hang at ~100% (sometimes even saying the application is not responding in red) but will almost always complete the cycle if I let it go for 30 minutes or so.  As long as I leave Excel alone while it is working it will not crash.  I had not thought of using the Activity Monitor as you suggested. Also I did not realize using a 32 bit application limited me to 4GB of memory for each application.  That is clearly a problem for this kind of work.  Is there any work around for this?   It seems like a 64-bit spreadsheet would help.  I would love to use the new 64 bit Numbers but the current version limits the number of rows and columns.  I tried it out on my MacBook Pro but my files don’t fit.
    The hatter,
    This may be the solution for me. I’m OK with assembling the unit you described (I’ve even etched my own boards) but feel very bad about needing to step away from Apple products.  When I started computing this was the sort of thing computers were designed to do.  Is there any native 64-bit spreadsheet that allows unlimited rows/columns, which will run on an Apple?  Excel is only 64-bit on their machines.
    Many thanks to both of you for your quick and on point answers!

  • Just upgraded IOS to V7 and iphone is asking for a password and the online password will not work. I really need to get this sorted as I am away and need to get the phone working.

    Just upgraded IOS to V7 and iphone is asking for a password and the online password will not work. I really need to get this sorted as I am away and need to get the phone working.

    Pablos1966 wrote:
    Surely the current ID and Password would work . Anyway I will see how I get on with the Device Password.
    No. If you failed to turn off Find my iPhone BEFORE you upgraded to iOS 7, you will need the original Apple ID and password. If you upgraded to iOS 7 you will need this info; there is no way around this. If it is the device passcode you will need to restore your iPhone in order to reset that, which in the end will require your Apple ID and password in order to activate the phone once it is restored.
    Why don't you have the original Apple ID? Where did you get the phone?

  • HT204053 My husband and I both have iPhones but we only have one iPad. We use the same apple ID because we also share the same email address. How would this work with iCloud because we don't share the same contacts?  Thanks Elainecontacts

    My husband and I both have an iPhone and we share an iPad. We also share the same email address so how would this work with iCloud because we don't share all the same contacts?
    Thanks

    An icloud account is designed to be used by one user.  That user can have all his/her devices synced with the same Apple data (email, contacts, calendars, notes, reminders, etc.) .  When two people use the same account, then problems usually occur when one user edits data that the other user doesn't want changed on their device.  You can continue sharing the same ID for the itunes account in order to share the purchased music, apps, etc.  itunes accounts and icloud accounts are different.
    It's by far better that each user has his/her own icloud account.

  • Upgrade Error 1604 - Would this work to get iphone OS 3.0 running?

    Last week, I tried to update my iPhone 3G with the new 3.0 OS only to get the 1604 error and what I had originally thought was a bricked iPhone. After some digging on these forums, I figured out how to revert back to the older OS. I found it on the internet, downloaded it, and then restored my iPhone using that. My question is, if I were to go about manually downloading the 3.0 OS from the internet to my computer, and then restoring my iPhone using it, would it work? My god, all I want to do is have the new OS on my iPhone! What the heck is going on?

    I can send invitations and accept invitations through my Exchange Calendar, but not through my gmail CalDav?
    Why would this be removed and not included? Is this feature going to be added next year and advertised as some new feature that other phones don't have, like cut and paste? My Dell PoctetPC from 2000 has cut and paste...
    Come on Apple - listen to users and bring in all of the basics! You want this to be fully recognized in the Enterprise - CalDav meeting invites are going to be necessary!

  • I have an imac bought late 2013, can i use it as a display for the new mac pro? I also want to use windows 8 on it, would this work with parallels or bootcamp?

    I have an imac bought late 2013, can i use it as a display for the new mac pro? I also want to use windows 8 on it, would this work with parallels or bootcamp?

    Yes, it supports target display mode. Windows can be run with either Parallels or Boot Camp.

  • I want to get another 4s and use it not as a phone, but only as a video camera and editor and hook it up only with wifi. i would sync it to itunes so i can pay for apps and upload. would this work, or must it be connected to a phone carrier?

    I want to get another 4s and use it not as a phone, but only as a video camera and editor and hook it up only to wifi. i would sync it to itunes so i can pay for apps and upload. would this work, or must it be connected to a phone carrier?

    Trust me when I say this coming from 20 years of experience.
    Get a powered external drive, format it 1 Partition Option: GUID and OS X Extended Journed as the format in Disk Utility.
    Download and install Carbon Copy Cloner, clone internal drive to external drive.
    Set a schedule to remind you to do it at least once a week, keep it near your charger.
    When you plug your charger in, do plug the clone and power the machine up, set the display to sleep only,
    CCC will do the rest.
    If you want to boot from it, hold the option/alt and select it Startup Manager.
    I've seen many TimeMachine and TimeCapsule nightmares and so far haven't seen a problem from anyone using a bootable clone.
    It's simple, it's easy, it's more reliable and more powerful than what Apple does and it only takes plugging in a extra cable.
    Make as many clones as you want, keep them time seperated, off site etc. etc.
    Cables don't have network issues, clones can be verified in seconds merely by booting from them.
    Clones protect your productivity, your up in seconds on a clone despite even the hard drive dying.
    Software problem? No sweat, boot of the clone and reverse clone your problems away.
    If you want to fuss and muss with half implemented TimeMachine and TimeCapsule network headaches then prepare to suffer.
    I don't like to suffer, I bought a Mac not to suffer, but it appears you do with TimeMachine and TimeCapsule.
    Most commonly used backup methods

  • While listening to a podcast on my iPhone I can e-mail the podcast ID. The email contains the url for the specific podcast. So you would assume that you could put that url into iTunes and it would take you to the podcast. This used to work but no longer.

    While listening to a podcast on my iPhone I can e-mail the podcast ID to share it with someone else. The email contains the url for the specific podcast. So you would assume that you could put that url into iTunes and it would take you to the podcast. This used to work but no longer. Months ago when I would e-mail myself the url all I had to do was click on the link in the e-mail and it took me right to the specific podcast in iTunes. Now it only opens iTunes and I can't figure out how to find the specific one. What good is the e-mail tab on the iPhone if it doesn't connect you to the podcast you sent?

    Same here. I just posted a question too.

Maybe you are looking for