Bottom Up Merge Sort

I am trying to implement merge sort in an iterative manner. I keep receiving an index out of bounds error, but I cannot tell what is causing it. Can anyone help point out where this is happening? My code is below. The variable count is there simply to keep track of the number of comparisons made. Sorry about it not being in code format. I am unsure how to do it in this forum.
public class ArraySort {
private static long[] a;
private int nElems;// number of data items
private static int count = 0;
public ArraySort(int max)
a = new long[max];
nElems = 0;
public static void merge(long [] arr, long[] temp, int left, int middle, int right){
          for(int i = left; i < middle; i++){
               temp[i] = arr;
          for(int k = middle; k < right; k++){
               temp[k] = arr[middle + right - k - 1];
          int i = left;
          int j = right - 1;
          for(int n = 1; n < right; n++){
               count++;
               if(temp[j] < temp[i]){                   *****This is the line that throws the exception********
                    arr[n] = temp[j--];
               else{
                    arr[n] = arr[i++];
     public static void mergesort(long[] arr){
          long[] temp = new long[arr.length];
          for(int i = 1; i < arr.length; i = i + i){
               for(int k = 0; k < arr.length - i; k+= i + i){
                    merge(arr, temp, k, k + i, Math.min(k + i + i, arr.length));          
     public int mergesort(){
          mergesort(this.a);
          return count;
Edited by: 799505 on Oct 1, 2010 6:34 PM
Edited by: 799505 on Oct 1, 2010 7:15 PM
Edited by: 799505 on Oct 1, 2010 7:39 PM

799505 wrote:
I am trying to implement merge sort in an iterative manner. I keep receiving an index out of bounds error, but I cannot tell what is causing it. Can anyone help point out where this is happening?Your computer already did point that out. You got a stack trace after that error message, right? The stack trace tells you what line of code threw the exception. Without that information it is extremely difficult to find that out, but with that information it's trivial. So look at the stack trace. If you can't figure out what it's telling you then post it here.

Similar Messages

  • Recursive merge sort, how does it work?

    hey friends
    I am stuck up with the code of recursive merge sort and am unable to understand as to how is the recursion working. Im posting the code for the merge sort and telling the details of where im facing the problem, if someone could explain me with an example as to where does the control go.
    im not posting the working code but just the part where im facing confusion.
    void mergesort(int[] a,int[] tmpa,int left,int right)
    if(left<right)
    int center=(left+right)/2;
    mergesort(a,tmpa,left,center);//1
    mergesort(a,tmpa,center+1,right);//2
    merge(a,tmpa,left,center+1,right);
    }plz explain as to how is the control being transferred in the two recursive calls labelled 1 and 2 in the above code. take for eg a series
    4,2,5,7,1,8 to be sorted
    thanks.

    i am having trouble figuring out these two sttements
    in the code
    mergesort(a,tmpa,left,center);//1
    mergesort(a,tmpa,center+1,right);//2
    ie the recursive calls. when will the //2 be
    executed? After //1.
    . what will be the values of center+1,right
    at which it starts executing ?Print them out or use a debugger to see for yourself. Better still, try to work through it by hand first and then use the print statements or debugger to see if you were right.
    basically im having trouble with the recursive
    calling. i have had read the tutorials but those are
    for simple cases like factorial etc. if someone can
    explain this in detailIt's the same priniciple. You start with the big piece, make a recursive call an a part of it, make a recursive call on a part of that, and so on. Ultimately, you get down to the smallest piece--the stopping condition--and you do the simple operation on that the results of that feed back up to the previous call, and its results feed back to the one before that, and so on until the second call's results feed back to where you called it on the whole thing.
    It's really probably much easier to observe than to try to understand from an explanation though.

  • Merge sort not working

    so i've been trying to write a merge sort algorithm for linked lists for an assignment and i'm so fing close, but it's really frustrating me because it isn't working correctly. i have a sort and a merge method and i'm doing this recursively. can someone point out what i'm doing wrong?? it prints the elements (i've been testing with random strings) and even changes their order, but no luck on them actually being sorted. help is massively appreciated.
    sort method:
    public static <T extends Comparable<T>> void sort(ADTListInterface<T> list){  
         int s = list.size();
    if (s<2)return;
    MyLinkedList<T> listl = new MyLinkedList<T>();
    MyLinkedList<T> listr = new MyLinkedList<T>();
    int x=0;
    for(; x<s/2; x++){
         listl.add(list.get(x));//add first half of list to new list
    for(; x<s; x++){
         listr.add(list.get(x));//add rest of original list to new list
    sort(listr);
    sort(listl);
    merge(listl, listr, list);     
    merge method:
    public static <T extends Comparable<T>> void merge(ADTListInterface<T> listl,ADTListInterface<T>
         listr,ADTListInterface<T> list){
         while(!listl.isEmpty() && !listr.isEmpty()){
              if(listl.get(0).compareTo(listr.get(0))<= 0){//select smaller element and put back in original list
                   list.remove(listl.get(0));
                   list.add(listl.get(0));
                   listl.remove(0);
              else{
                   list.remove(listr.get(0));
                   list.add(listr.get(0));
                   listr.remove(0);
         //if anything is left in remaining lists put elements into original list
         while(!listl.isEmpty()){
                   list.remove(listl.get(0));
              list.add(listl.get(0));
              listl.remove(0);
         while(!listr.isEmpty()){
                   list.remove(listr.get(0));
              list.add(listr.get(0));
              listr.remove(0);
    }

    i've been testing with random stringsIt would be better to test on specific things, eg from simple to complex. For example, test it with:
    -an empty list
    -"a"
    -"a","b"
    -"b", "a"
    -"c","b","a"
    continue until your sorting fails, then find out why it fails there and not on the previous test.

  • External Multi Way Merge Sort in Java!

    Hi guys,
    some month ago I've sent [this post|http://forums.sun.com/thread.jspa?forumID=31&threadID=5310310] to the Java Programming Forum to notify the availability of an External Multi Way Merge Sort written in Java, tuned and tested over GB of text data and under LGPL license, that can help you in dealing with huge logs or CVS files.
    I want here just to notify you about this implementation.
    You can run the sorting algo via command line or you can call from any Java class instantiating the ExternalSort class, setting its properties, and calling run().
    Searching in the forum I saw many people that ask for an help in sorting huge textual files that doesn't fit in memory. My post solve this problem, but I think that very few people are aware of it :( ....
    Hope to help who need this feature. See you!

    Nice work this SmallText,
    did not try it, but like the idea
    I have been doing something similar in c (long, long time ago) and what made our compression really tight for typical csv files was decision to build one huffman coder for each field. The trick was to include field separator symbol into static huffman coder for every field, that provides you with End Of Field signal where to switch to next decoder.
    for ExternalSort, I would suggest to make it multithreaded. Having so many many cores and low prices of ram today, it makes a lot sense. Easy way to do it is to have IO_Thread(s) and Worker_Threads (the first ones do read and write and second ones are for sorting).... this is powerfull as you utilize many cores and can easily extend some processing (like compression, token frequency counting or whatever...) via callbacks in each phase (chunking/sorting/merging)
    again, congrats, really nice work

  • Merge Sort - 'almost' working

    Hello everyone!
    I have been learning how to program for a while and I thought it came time for algorithms. I bought Cormen's book and everything was going smoothly until it came to Merge Sort. I understand the theory but I am having trouble putting it into practise. I found online a few (working) examples (like this one: http://goo.gl/75R0z) and I tried to look up to them and write my own code (with slight changes) and so far so unsuccessful. The code compiles but it doesn't do it's thing. Can you give me a hand?
    main function:
    http://pastebin.com/y0HZ7Dkj
    Here's the algorithm:
    http://pastebin.com/U8XAKsiv

    BR41N-FCK wrote:
    If I had a project with a short deadline - sure, I'd use a pre-made (what else can we call it?) solution. But right now I am learning algorithms, so there's no point using ready ones.
    The only reason for the sorting and linked-list exercises is to give students some experience with challenging, but solvable problems in programming. Don't get me wrong, there is great value in that. However, it would be better done in C or even Pascal. Computer Science teaching kind of went off the deep end in 1990 or and has only gotten worse.
    Thank you for solving my problem. It was so simple... and maybe that's why I have overlooked it :-)
    One of the skills a programmer must have is how to debug such problems. That doesn't always mean running in a debugger. I very rarely use a debugger. Most modern, UI or server work is far too complex for such things. Simple "printf" statements are usually all that is required.
    Speaking of C++. Why would you call it awful? I mean it isn't the best for developing windowed apps (see: objective-c and c# on windows), but it is great for console ones and also it is good for education purposes thanks to its plain syntax (compared to c# and not to even mention the crazy syntax of objective-c).
    Because I wasted so much of my programming career on it. I suppose it was a valuable lesson. I suspose if someone had told me it was junk in 1995 I probably would have ignored them then. Now I have a decent store of tacit wisdom that is hard to explain. I just "know" when someone does or doesn't know what they are talking about. Just because "everybody is doing it" doesn't mean everybody isn't wrong.
    Objective-C syntax is actually quite simple. It is just the message passing through brackets. That is insignificant compared to cryptic C++11. You aren't even using C++ in this program. With the expection of iostream, you are only using C. I don't see any templates, no references, no const-correctness, no virtual functions, no inline code, no iterator traits, no lambdas, no locales, no iomanips. It's all junk that only makes life harder and life is short enough as it is.

  • A problem on merge sort

    This merge sort test can not run as expected.
    Can any one check it for me? Thank you
    Source code attached
    //MergeSort.java
    //application to show the mergesort
    public class MergeSort{
         public static void main(String [] args){
              if(args.length == 0){
                   System.err.println("Format: java mergeSort [number1] [number2]...");
                   return;
              int [] sortList = new int[args.length];
              try{
                   for(int i = 0 ; i < args.length ; i ++){
                        sortList[i] = Integer.parseInt(args);
              catch(NumberFormatException ex){
                   System.err.println("Input format error, only integer numbers before error been sorted");
              mergeSort(sortList, 0, sortList.length-1);
              System.err.print("Sorted list : ");
              for(int i = 0 ; i < sortList.length ; i ++)
                   System.err.print(sortList[i] + " ");
         public static void mergeSort(int [] sortList, int first, int last){
              if(first < last){
                   int mid = (first + last) / 2;
                   mergeSort(sortList, first, mid);
                   mergeSort(sortList, mid + 1, last);
                   merge(sortList, first, mid, last);
         private static void merge(int [] sortList, int first, int mid, int last){
              int indexLeft = first;
              int indexRight = mid + 1;
              int indexTemp = 0;
              boolean isEmpty = false;
              int [] tempList = new int[sortList.length];
              while(!isEmpty){
                   if(sortList[indexLeft] < sortList[indexRight]){
                        tempList[indexTemp] = sortList[indexLeft];
                        indexLeft++;
                   else{
                        tempList[indexTemp] = sortList[indexRight];
                        indexRight++;
                   indexTemp ++ ;
                   if(indexLeft > mid||indexRight > last)
                        isEmpty = true;
              while(indexLeft <= mid){
                   tempList[indexTemp] = sortList[indexLeft];
                   indexTemp++;
                   indexLeft++;
              while(indexRight <= last){
                   tempList[indexTemp] = sortList[indexRight];
                   indexTemp++;
                   indexRight++;
              for(int i = first ; i <= last ; i++)
                   sortList[i] = tempList[i];

    Use code tags.
    Does this look like a debug for free forum to you?
    What isn't working? A compile error? I see a syntax error in your code.
    What is the input, what is the output?

  • Group sort / merge sort

    Is there any way i can do group sort/merge sort thru PL/SQL.
    Output Example:
    number course
    1000 MATH
    SCI
    LANG
    1040 MATH
    SCI
    Can we do this?

    are you looking for this?
    here is example from emp table at sqlplus
    SQL> break on dno
    SQL> select dno,ename from emp where dno in(10,20)
      2  order by 1;
           DNO ENAME
            10 CLARK
               KING
               MILLER
            20 SMITH
               ADAMS
               FORD
               SCOTT
               JONES

  • Sort Order on Merge documents

    OK. I have a group in address book. It shows alpha order on surname.
    I do a merge with Pages and send to the printer and get documents out in no sensible order.
    This has probably been answered lots before but I can't find it on a search.
    Anyone know how to control the Pages merge output order ?
    Regards
    Eric

    I had the same problem. Here is how I got my mail merge to merge sorted.
    In Address Book I created a group with all the addresses I wanted to use. Then I clicked on that group and did a select all. Then I dragged and drop the addresses onto my pages document and it created a sorted mail merge.

  • IPhoto Questions:  Merge and Sort;  Cropping;  Collage

    Hello,
         I have some iPhoto questions:
         (1)  I have several different photos from different sources of my son's wedding.  I have merged the photos into one album and sorted them by date in iPhoto, but they are still showing all over the place.  How do I merge/sort them so that they all show in chronological/date & time order?
         (2)  I can only crop in square or rectangular shape.  Does iPhoto have a way of cropping using different shapes like heart, circle, triangle, etc?
         (3)  I cannot seem to find a way to create a collage in iPhoto where I can put 2 or more photos in one frame.  Is there a way for iPhoto to do this?
         I am not sure if these are iPhoto limitations or I need an upgrade to a version that can do all these?
    Thanks...

    As it merges the libraries iphoto library manager will ask you what you want to do with duplicates. However, remember files with different sizes are not duplicates. Also importing one library to another is not a good idea. You'll get a mess of different versions of files treated as new imports, so that's no way to merge.

  • Help with using mergesort to sort a list of names alphabetically?

    Hi, I'm trying to sort a list of names alphabetically, case-insensitive by using the mergesort technique.
    I wrote this code and when I trace it through on paper with an example array of names, it should work, but when I run it with an actual txt file, it's not correctly alphabetical.
    I'd appreciate it if someone could take a look at my code and give me some ideas on what my problem might be.
    Thanks in advance! (note: I also posted this question to java-forums.org, as I've been working on this little problem for over five hours and am in desperate need of some help!)
    public static void mergeSort(String[] names) 
            if (names.length >= 2) 
                String[] left = new String[names.length/2]; 
                String[] right = new String[names.length-names.length/2]; 
                for (int i = 0; i < left.length; i++) 
                    left[i] = names;
    for (int i = 0; i < right.length; i++)
    right[i] = names[i + names.length/2];
    mergeSort(left);
    mergeSort(right);
    merge(names, left, right);
    // pre : result is empty; list1 is sorted; list2 is sorted
    // post: result contains result of merging sorted lists;
    // add merge method below
    public static void merge(String[] names, String[] left, String[] right)
    int i1 = 0;
    int i2 = 0;
    for (int i = 0; i < names.length; i++)
    if (i2 >= right.length || (i1 < left.length && left[i1].compareToIgnoreCase(right[i1])<0))
    names[i] = left[i1];
    i1++;
    } else
    names[i] = right[i2];
    i2++;

    Welcome to the forum.
    Please read this to learn hot to format your code (and other things relevant for this forum):
    https://forums.oracle.com/forums/ann.jspa?annID=1535
    923566 wrote:
    Hi, I'm trying to sort a list of names alphabetically, case-insensitive by using the mergesort technique.
    I wrote this codeDo you know the <tt>TreeSet</tt> class?
    http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
    With that sorting Strings is a two liner:
    http://www.java2s.com/Code/Java/Collections-Data-Structure/TreeSetDemo.htm
    bye
    TPD

  • IPod Touch Graphics Weirdness - Status Bar mirrored at bottom of screen!!!

    Okay, this is VERY weird and I have no idea what's going on - This morning when I woke up, I grabbed my trusty iPod Touch (4th Gen, 32GB with iOS 5) to check my calendar and noticed that the Status Bar (if I'm calling it the right thing - the white bar at the very top of the screen that shows the time, battery charge, WiFi signal,etc) was not only at the top - but also at the BOTTOM of the screen too!
    The mirrored Status Bar has the correct time and battery life as the top and the time updates just as it should. I can also see the lock icon when I first turn it on. However, to the extreme left the bottom bar is sort of "washed out" and is so white that I can't make out the word "iPod" that shows on the top bar. In fact, it's also sort of translucent as I can see the dock, icon name and part of my wallpaper behind/thru it! I also just realized something else weird - if I pull down the Notifications panel, I can see the notification panel sort of "scrolling" thru the bottom Status Bar!!! I hope I'm explaining this well enough - but it's like..I dunno, like the ideo memory for the top of the screen is being mirrored over the bottom of the screen too - I can see what should be there as well, it;s like it's overlayed or something. The Notification panel is especially weird since it totally obsured the top status bar as it's being pulled down - and this is exactly what the bottom status bar area shows me - what's in the section in the top bar is prescisely what is showing in the bottom bar section!!!!
    It stays displayed along the bottom no matter what app I'm in, even a full screen video, game, lock screen, etc; nor does it disappear when rotating to landscape mode - it still stays in the exact same place (tho in landscape it's now on the right side as it were). I have soft reset, synched, etc but it wil not go away. As I said, I deleted all recently installed packages, but I didn't install anything the night before (remember I just found it this way this morning) - i.e. I wasn't doing anything weird or experimental or anything remotely like that with my beloved little iPod (never JailBroken it or any of that stuff - am happy as it is and never been tempted to do anything like that to it). I also have never used any of the AV Out cables or whatever they are called that allow you to mirror an iPod screen on a TV or monitor or whatever - never used anything but the sync cable (now at my sisters), my Belkin charge auto charge cable, and that's it (I'm mentioning all this since I see other people asking this sort of thing for other problems when I was trying to find anyone else experiencing/ed this issue).
    I have not tried a factory restore yet, and wanted to post here before I go that route to see if this is maybe something Apple has seen before and can offer a quick and easy fix. Otherwise I'm guessing a hard/factory reset is the only way to go - I'm a bit worried about this since (of course) my sync cable is no longer here - gave it to my sister the last time she was in town and have just been using my charge cable (no sync capabilities, just power) since I don't really need it with iOS5's wonderful WiFi Sync. I do use iCloud - but if I hard reset/factory reset, will iCloud restore the synching info so I can sync all my apps and music & videos back via iTunes from my Laptop, or will I need to buy another sync cable? IF factory reset is the only way, please let me know (anyone that knows!) what I'm in for in regards to restoring from iCloud if anyone here is experienced with that. I know my non-iTunes music and videos are not backed up in the Cloud, but as long as it restores the ability to sync wirelessly with iTunes on my Laptop that's fine. Asuming, of course, that a factory reset will even fix this Status Bar oddity - I'm really afraid it means my little iPod's internal board is going fry-happy or something awful like that. :-(
    I tried taking some screen snapshots (home + power off) to post, however the camera roll just displays a standard beautiful looking screen, no double bar - not sure what that indicates. However after some fiddling and emailng to myself,  I do have a couple pics posted below. I apologize for the lack of quality - I took them - and don't laugh - with my Android Phone (yes, I have every intention of upgrading to an iPhone 4S as soon as I can - having a bit of enforced financial conservatism going on at the present unfortunately - which is one of the main reasons I'm so worried my beloved iPod Touch 4 is having issues as it's either very close to warranty expriration and can't afford another right now, and really don't want to have to rely on my Android Phone for everything I do on my iPod Touch - there truly is no comparison!).
    If anyone has any ideas or has seen something similar please let me know! I did search the Apple forums prior to posting this, and even googled the web but could find nothing like this ever happening to anyone else. I absolutely love my iPod Touch and would be uterly lost without it, so I'm hoping with all my might that this isn't some sign of a bad board or something in my beloved little beautiful iPod Touch!
    Thanks in advance for any assistance, suggestions, etc!!!
    NewtonDKC
    Message was edited by: NewtonDKC (embarrassing spelling errors corrected and a couple additional discoveries added!) :-)

    I understand the various methods - I was just worried because I've never restored via iCloud - from the limited experience I've had thus far, I'm impressed! But of course if Apple does it, it's going to be the best experience possible! :-)
    And as you may have guessed from my now having iCloud restore experience, it is due to me going ahead and trying a reset to factory settings/wiping it clean. And unfortunately - the bottom bar is STILL THERE! <much argghhing! and %^$#@*&^%$'ing loudly>
    I did try wiping it a couple of times, but no joy. At this point, I'm guessing this means there's something majorly wrong with the graphics subsystem and/or main board? It's not a screen issue as it's working fine - in fact it's working double-time displaying two things at once - dimensional transcendentalists take note! <grin>
    So unless anyone else has some fantastically bright ideas, I'm guessing this means I need to call Apple next? I'm guessing one of these pages has the appropriate contact info - I'm just not at all looking forward to being without my favorite gadget in the history of gadgetdom (and as you can tell from my username, I've been a fan of Apple Gadgets for quite awhile now!).
    Anyone know if Apple offers any advanced replacement options? Or if there's anyway to tell if my Touch is stil under warranty? I can't remember the exact purchase date but probably coming up very soon - have they been out a year? Sorry if thee questions are silly, as I said, I'm a newbie to Apple Support - first Apple product I've ever owned that broke!
    Thanks for any info for anyone coming in late to the fun, and/or for any tips on who/what to call and ask about.
    Wish me luck! :-0
    Newt

  • How to display the steps of a sort algorithm??

    I'm having a lot of trouble trying to display the results of applying a merge sort to a set of 10 integers. The problem is not that I can't see anything on the text area within the applet, the problem is that I am getting a lot of repetitions and duplicates occuring. I have tried inserting the Display() method in various positions in the sort, I have set up a temporary array to compare the elements of the array before and after the particular step of the sort is applied and an if statement to display only if there are changes have happened to the array. Can anyone advise?? Here's the code for the sort, including my current attempt to get the sort diplayed in steps:
    public class MSort extends JFrame
    public MSort(int[] anArray, JApplet anApplet)
    a = anArray;
    applet = anApplet;
    ArrayUtil.Display(a,textArea);
    JumpLine(textArea);
    Sorts the array managed by this merge sorter
    public void sort()
    throws InterruptedException
    mergeSort(0, a.length - 1);
    textArea.append("End of Merge Sort");
    Sorts a range of the array, using the merge sort
    algorithm.
    @param from the first index of the range to sort
    @param to the last index of the range to sort
    public void mergeSort(int from, int to)
    throws InterruptedException
    if (from == to) return;
    int mid = (from + to) / 2;
    mergeSort(from, mid);
    mergeSort(mid + 1, to);
    merge(from, mid, to);
    Merges two adjacent subranges of the array
    @param from the index of the first element of the
    first range
    @param mid the index of the last element of the
    first range
    @param to the index of the last element of the
    second range
    public void merge(int from, int mid, int to)
    throws InterruptedException
    startPosition = from;
    endPosition = to;
    int n = to - from + 1;
    // size of the range to be merged
    // merge both halves into a temporary array b
    int[] b = new int[n];
    int i1 = from;
    // next element to consider in the first range
    int i2 = mid + 1;
    // next element to consider in the second range
    int j = 0;
    // next open position in b
    int[] oldArray = new int[a.length];
    System.arraycopy(a, 0, oldArray, 0, oldArray.length);
    // as long as neither i1 nor i2 past the end, move
    // the smaller element into b
    while (i1 <= mid && i2 <= to)
    if (a[i1] < a[i2])
              b[j] = a[i1];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    i1++;
    else
    b[j] = a[i2];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    i2++;
         pause(2);
    j++;
         for (int k=0; k < a.length-1; k++) {// method I've put in to                  try and compare the array b4 and after the sort
    if (a[k] != oldArray[k]){
    ArrayUtil.Display(a,textArea);
    JumpLine(textArea);
    // note that only one of the two while loops
    // below is executed
    // copy any remaining entries of the first half
    while (i1 <= mid)
    b[j] = a[i1];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    //ArrayUtil.Display(a,textArea);
                        //JumpLine(textArea);
    pause(2);
    i1++;
    j++;
    // copy any remaining entries of the second half
    while (i2 <= to)
    b[j] = a[i2];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
         } pause(2);
    i2++;
    j++;
    // copy back from the temporary array
    for (j = 0; j < n; j++)
    a[from + j] = b[j];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    pause(2);
    public void pause(int steps)
    throws InterruptedException
    if (Thread.currentThread().isInterrupted())
    throw new InterruptedException();
    applet.repaint();
    Thread.sleep(steps * DELAY);
    private int[] a;
    private int startPosition = -1;
    private int endPosition = -1;
         private JTextArea textArea = SortApplet1.getTextArea2();
    private JApplet applet;
    private static final int DELAY = 100;
    public static void JumpLine(JTextArea t){
         JTextArea TxtArea = t;
         TxtArea.append("\n\n");
    }

    see sample at http://lwh.free.fr/pages/algo/tri/tri.htm
    marvinrouge

  • N^2 log(n) for Collections.sort() on a linked list in place?

    So, I was looking over the Java API regarding Collections.sort() on linked lists, and it says it dumps linked lists into an array so that it can call merge sort. Because, otherwise, sorting a linked list in place would lead to a complexity of O(n^2 log n) ... can someone explain how this happens?

    corlettk wrote:
    uj,
    ... there are other sorting methods for linked lists with an O(N*N) complexity.Please, what are those algorithms? I'm guesing they're variants off insertion sort, coz an insertion is O(1) in a linked list [and expensive in array]... Am I warm?You don't have to change the structure of a linked list to sort it. You can use an ordinary Bubblesort. (The list is repeatedly scanned. In each scan adjacent elements are compared and if they're in wrong order they're swapped. When one scan of the list passes without any swaps the list is sorted). This is an O(N*N) algoritm.
    What I mean is it's possible to sort a list with O(N*N) complexity. It doesn't have to be O(N*N*logN) as the Java documentation kind of suggests. In fact I wouldn't be surprised if there were special O(N*logN) algoritms available also for lists but I don't know really. In any case Java uses none of them.

  • Group and Merge Delimited List

    Hi All
    Is there a way we can sort the result of Group and Merge processor->Delimited list values ?
    I see none in the options and it seems sorting them in alphabetical order.
    Thanks,
    Sid

    Hi Sid,
    Yes, the "Delimited List" selection function in Group and Merge sorts the results into ascending alphabetical order. This was a deliberate decision so that the results of the processor are deterministic and agnostic of the order of the records entering the processor. It is not possible to change this sort order inside the processor but if required you can perform downstream post-processing of the data if you need to change the order.
    thanks,
    Nick

  • Apple Script to Sort through the Address Book

    Dear All,
    I am quite new to Apple and just a learner on Apple-scripts. Its been quite a task to learn.. I would require some help on a few things..
    The script will eventually use numbers to send email and get the user inputs and any yet to reach there..
    After going through lots of scripts to sort through the address book and make a clean address book, i found they are quite slow in processing takes about 20~30 Minutes to get through 2000 Contacts..
    Hence after reading posting of Mr. Koenig & Mr. Hiroto and specifically on deep copy. I have written the following code which does the following on 2000 records within 6~8Mins.
    The Script work its way through all the contact is the address List.. and creates Groups
    1. Duplicate Email Id's — List of Contacts with same email ID's including Contacts where the email Id is entered twice.. (Strange.. Address Book Issue, copy of the email Id under work & home)
    2. Duplicate Phone — List of Contacts with same Phone Numbers including Contacts where the Phone Nos is entered twice.
    3. Duplicate Name — List of Contacts with Same Names
    4. Duplicate No Name — List of Contacts without the First Name and Last Name
    it also sort the Contacts under the following Group which you can edit later with all the information's..
    1. Only Email Ids — List of Contacts with Email ID and No Phone Numbers
    2. Only Phone — List of Contacts with Phone Numbers and No Email Id's
    3. No Email or Phone — List of Contacts with No Email Id's and No Phone numbers (some half completed contacts )
    My Question to the forum is why is the following code still taking too much time..
    set onlyDupEList to every person of group theGroupEmail
    repeat with j from 1 to count of Dup_email
    set tempdata to item j of Dup_email
    if onlyDupEList does not contain {tempdata} then add tempdata to group theGroupEmail
    end repeat
    save application "Address Book"
    and the scripts slows down when the items in the list is quite large (over 800 or so )..
    Any help is appreciated and thanks in advance..
    -- the code ---
    global MsgTitle
    on run
    set MsgTitle to "Search for Duplicates in Address Book Contacts"
    display dialog ¬
    "This Script takes a while to finish" & return & "maybe 10 min or More..." & return & "Depending on the Address Book Contacts." & return & return & "Hence Allow it to run for the while" with title MsgTitle ¬
    with icon 1 ¬
    buttons {"Continue"} ¬
    giving up after 5
    set question to display dialog "Select the Duplicate Search Parameter " with icon 1 with title MsgTitle ¬
    buttons {"Contact Name", "Contacts on Phone & Email Id's", "Quit"} default button 3
    set rtnValue to button returned of question
    if rtnValue is "Quit" then
    -- tell application "Address Book" to quit
    tell me to quit
    end if
    if rtnValue is "Contact Name" then
    -- tell application "Address Book" to quit
    GetDup_byName("Duplicate Name")
    end if
    if rtnValue is "Contacts on Phone & Email Id's" then --Contacts on Phone & Email Id's
    -- tell application "Address Book" to quit
    Get_dup()
    end if
    end run
    --- Search on Name Field ---
    on GetDup_byName(theGroupName)
    set question to display dialog "Do you want to search for duplicates based on Names? " with icon 0 with title MsgTitle ¬
    buttons {"Continue", "Quit"} default button 1
    set rtnValue to button returned of question
    if rtnValue is "Quit" then
    -- tell application "Address Book" to quit
    tell me to quit
    end if
    tell application "Address Book"
    activate
    set biglist to {}
    set NoNameList to {}
    set theGroupNoName to "Duplicates No Names"
    set theGroup to theGroupName
    -- if not (exists (group "Dupilicate Entries")) then
    if not (exists (group theGroup)) then
    make new group with properties {name:theGroup}
    save
    end if
    if not (exists (group theGroupNoName)) then
    make new group with properties {name:theGroupNoName}
    save
    end if
    set the_names to name of people
    repeat with i from 1 to number of items in the_names
    set theName to item i of the_names
    -- return theName
    if theName is not in biglist then
    copy theName to end of biglist
    else
    set counter to (people whose name is theName)
    if (count of counter) > 1 then
    repeat with i from 1 to number of items in counter
    set this_item to item i of counter
    -- display dialog this_item
    add this_item to group theGroup
    end repeat
    -- return counter as string
    end if
    end if
    -- captures the Contacts without Name ---
    if theName contains "@" then
    -- display dialog theName
    set counterList to (people whose name is theName)
    repeat with i from 1 to number of items in counterList
    set this_item to item i of counterList
    -- display dialog this_item
    add this_item to group theGroupNoName
    end repeat
    end if
    -- save application "Address Book"
    end repeat
    save application "Address Book"
    set peopleCount to (count every person)
    -- set peopleCount to 50 -- only for testing --
    repeat with i from 1 to peopleCount
    set first_name to first name of person i as string
    set Last_Name to last name of person i as string
    if first_name is equal to "missing value" and Last_Name is equal to "missing value" then
    -- display dialog first_name & " : " & Last_Name
    set end of NoNameList to (id of person i)
    end if
    end repeat
    repeat with j from 1 to the count of NoNameList
    set tempdata to item j of NoNameList
    -- set testdata to person id tempdata
    -- if (name of groups of testdata does not contain theGroupNoEmail) then
    add tempdata to group theGroupNoName
    -- end if
    end repeat
    save application "Address Book"*)
    display dialog ¬
    "This Script Finished Processing Address Book Contacts the Duplicates are in the group" with title MsgTitle ¬
    with icon 1 ¬
    buttons {"Continue"} ¬
    giving up after 5
    end tell
    end GetDup_byName
    on Get_dup()
    set question to display dialog "Do you want to search for duplicates based on Names? " with icon 0 with title MsgTitle ¬
    buttons {"Continue", "Quit"} default button 1
    set rtnValue to button returned of question
    if rtnValue is "Quit" then
    -- tell application "Address Book" to quit
    tell me to quit
    end if
    tell application "Address Book"
    activate
    set theGroupEmail to "Duplicate Email Id's"
    set theGroupPhone to "Duplicate Phone"
    set theGroupNoEmail to "Only Phone Numbers"
    set thegroupNoPhone to "Only Email Id's"
    set theGroupNoData to "No Email or Phone"
    -- set theGroup to theGroupName
    if not (exists (group theGroupEmail)) then
    make new group with properties {name:theGroupEmail}
    save "Address Book"
    end if
    if not (exists (group theGroupPhone)) then
    make new group with properties {name:theGroupPhone}
    save "Address Book"
    end if
    if not (exists (group theGroupNoEmail)) then
    make new group with properties {name:theGroupNoEmail}
    save "Address Book"
    end if
    if not (exists (group thegroupNoPhone)) then
    make new group with properties {name:thegroupNoPhone}
    save "Address Book"
    end if
    if not (exists (group theGroupNoData)) then
    make new group with properties {name:theGroupNoData}
    save "Address Book"
    end if
    set ListofPeople to people --the_ID
    set ListofEmailID to value of emails of people --the_emails
    -- return ListofEmailID
    set ListofPhones to value of phone of people -- the_phones
    -- return ListofPhones
    set biglist to {}
    set ListEmail_Uniq to {}
    set ListEmail_Dup to {}
    set No_PhoneList to {}
    set No_EmailList to {}
    set No_dataList to {}
    set FlagEmail to false
    set FlagPhone to false
    -- repeat with i from 1 to number of items in the_emails
    repeat with i from 1 to count of ListofEmailID
    set thePersonID to item i of ListofPeople
    set theEmails to item i of ListofEmailID
    if theEmails is equal to {} then
    set end of No_EmailList to thePersonID
    else
    -- set FlagEmail to true
    repeat with j from 1 to count of theEmails
    set tmpdata to item j of theEmails
    -- return tmpdata
    if tmpdata is not in biglist then
    set end of biglist to tmpdata
    set end of ListEmail_Uniq to {tmpdata} & {thePersonID}
    else
    set end of ListEmail_Dup to {tmpdata} & {thePersonID}
    end if
    end repeat
    end if
    end repeat
    -- return ListEmail_Uniq
    -- return ListEmail_Dup
    -- save application "Address Book"
    set biglist to {}
    set ListPhone_Uniq to {}
    set ListPhone_Dup to {}
    -- repeat with i from 1 to number of items in the_emails
    repeat with i from 1 to count of ListofPhones
    set thePersonID to item i of ListofPeople
    set thePhones to item i of ListofPhones
    if thePhones is equal to {} then
    set end of No_PhoneList to thePersonID
    else
    -- set FlagPhone to true
    repeat with j from 1 to count of thePhones
    set tmpdata to item j of thePhones
    -- return tmpdata
    if tmpdata is not in biglist then
    set end of biglist to tmpdata
    set end of ListPhone_Uniq to {tmpdata} & {thePersonID}
    else
    set end of ListPhone_Dup to {tmpdata} & {thePersonID}
    end if
    end repeat
    end if
    end repeat
    -- return ListPhone_Uniq
    -- return ListPhone_Dup
    set the Dup_email to {}
    -- Find the Duplicates from the sorted list --
    repeat with i from 1 to the count of ListEmail_Dup
    set tempdata to item i of ListEmail_Dup
    set dataEmailDup to item 1 of tempdata
    set dataPersonDup to item 2 of tempdata
    repeat with j from 1 to the count of ListEmail_Uniq
    set tempdata to item j of ListEmail_Uniq
    set dataEmailUniq to item 1 of tempdata
    set dataPersonUniq to item 2 of tempdata
    -- display dialog mainEmail1 & "=" & mainEmail2 & " " & mainID1 & "=" & mainID2
    if dataEmailDup is equal to dataEmailUniq then
    set end of Dup_email to dataPersonDup -- & "," & dataPersonUniq
    set end of Dup_email to dataPersonUniq
    end if
    (* -- the code takes lot more time if add to group was used --
    if dataEmailDup is equal to dataEmailUniq then
    set testdata to person id dataPersonDup
    add testdata to group theGroup
    set testdata to person id dataPersonUniq
    add testdata to group theGroup
    end if
    end repeat
    end repeat
    -- return Dup_email
    set the Dup_Phone to {}
    -- Find the Duplicates from the sorted list --
    repeat with i from 1 to the count of ListPhone_Dup
    set tempdata to item i of ListPhone_Dup
    set dataPhoneDup to item 1 of tempdata
    set dataPersonDup to item 2 of tempdata
    repeat with j from 1 to the count of ListPhone_Uniq
    set tempdata to item j of ListPhone_Uniq
    set dataPhoneUniq to item 1 of tempdata
    set dataPersonUniq to item 2 of tempdata
    -- display dialog mainEmail1 & "=" & mainEmail2 & " " & mainID1 & "=" & mainID2
    if dataPhoneDup is equal to dataPhoneUniq then
    set end of Dup_Phone to dataPersonDup -- & "," & dataPersonUniq
    set end of Dup_Phone to dataPersonUniq
    end if
    (*if dataPhoneDup is equal to dataPhoneUniq then
    set testdata to person id dataPersonDup
    add testdata to group theGroup
    set testdata to person id dataPersonUniq
    add testdata to group theGroup
    -- save
    end if*)
    end repeat
    end repeat
    -- return Dup_Phone
    set onlyDupEList to every person of group theGroupEmail
    repeat with j from 1 to count of Dup_email
    set tempdata to item j of Dup_email
    if onlyDupEList does not contain {tempdata} then add tempdata to group theGroupEmail
    end repeat
    save application "Address Book"
    set onlyDupPList to every person of group theGroupPhone
    repeat with j from 1 to count of Dup_Phone
    set tempdata to item j of Dup_Phone
    if onlyDupPList does not contain {tempdata} then add tempdata to group theGroupPhone
    end repeat
    save application "Address Book"
    set onlyPhoneList to every person of group theGroupNoEmail
    repeat with j from 1 to the count of No_EmailList
    set tempdata1 to item j of No_EmailList
    if No_PhoneList does not contain {tempdata1} then
    if onlyPhoneList does not contain {tempdata1} then add tempdata1 to group theGroupNoEmail
    end if
    (*set flagE to false
    repeat with i from 1 to the count of No_PhoneList
    set tempdata2 to item i of No_PhoneList
    if tempdata1 is equal to tempdata2 then
    set flagE to true
    exit repeat
    end if
    end repeat
    if flagE is false then add tempdata1 to group theGroupNoEmail*)
    end repeat
    save application "Address Book"
    set onlyEmailList to every person of group thegroupNoPhone
    repeat with j from 1 to the count of No_PhoneList
    set tempdata1 to item j of No_PhoneList
    if No_EmailList does not contain {tempdata1} then
    if onlyEmailList does not contain {tempdata1} then add tempdata1 to group thegroupNoPhone
    end if
    end repeat
    save application "Address Book"
    set onlyList to every person of group theGroupNoData
    repeat with i from 1 to count of ListofPeople
    if (item i of ListofEmailID is equal to {}) and (item i of ListofPhones is equal to {}) then
    set tempdata to item i of ListofPeople
    if onlyList does not contain {tempdata} then add tempdata to group theGroupNoData
    end if
    end repeat
    save application "Address Book"
    display dialog ¬
    "This Script Finished Processing Address Book Contacts the Duplicates are in the group" with title MsgTitle ¬
    with icon 1 ¬
    buttons {"Continue"} ¬
    giving up after 5
    end tell
    end Get_dup
    on quit
    --set MsgTitle to "Change Email ID's Domain Name"
    save application "Address Book"
    display dialog "Contact Srikanth Kamath at [email protected] for any Help" with title MsgTitle with icon 1 buttons "OK"
    continue quit
    end quit

    Hello Srikanth Kamath,
    I'm not sure you're still following this thread, but anyway here's sample code I said I'd post later.
    --SCRIPT2
    main()
    on main()
    script o
    -- input data
    property xx : {1, 2, 3, 4, 5} -- list of parents
    property yy : {{"g", "h"}, {"a", "b"}, {"b", "e", "f"}, {"e"}, {"c", "d"}} -- list of children per parent
    -- work list
    property pp : {} -- list of children tagged by parent; i.e, lits of {child, parent}
    property qq : {}
    property rr : {}
    -- (1) build list of children tagged by parent
    repeat with i from 1 to count my xx
    set x to my xx's item i
    set y to my yy's item i
    repeat with p in y
    set end of my pp to {p's contents, x}
    end repeat
    end repeat
    --return pp -- {{"g", 1}, {"h", 1}, {"a", 2}, {"b", 2}, {"b", 3}, {"e", 3}, {"f", 3}, {"e", 4}, {"c", 5}, {"d", 5}}
    -- (2) sort tagged list by child as key
    msort(my by_key1, my pp)
    --return pp -- {{"a", 2}, {"b", 2}, {"b", 3}, {"c", 5}, {"d", 5}, {"e", 3}, {"e", 4}, {"f", 3}, {"g", 1}, {"h", 1}}
    -- (3) retrieve parents with duplicate child
    (* retrieve list of {child, parent} for duplicate child *)
    set my qq to uniq(my eq_key1, my pp, {_dup:true})
    --return qq -- {{"b", 2}, {"b", 3}, {"e", 3}, {"e", 4}}
    (* retrieve list of parent *)
    repeat with q in my qq
    set r to q's item 2
    if r is not in my rr then set end of my rr to r
    end repeat
    return rr -- {2, 3, 4}
    end script
    tell o to run
    end main
    on by_key1(x, y)
    msort's comparator for list of lists
    key = item 1, ascending
    returns true iff x and y are out of order
    return x's item 1 > y's item 1
    end by_key1
    on eq_key1(x, y)
    uniq's comparator for list of lists
    key = item 1
    returns true iff x and y are considered equal
    return x's item 1 = y's item 1
    end eq_key1
    on msort(cmp_, aa) -- v1.2f2
    Basic recursive merge sort handler having list sorted in place.
    handler cmp_ : comparator
    * cmp_(x, y) must return true iff list element x and y are out of order.
    list aa : list to be sorted in place
    script o
    property parent : {} -- limit closure to minimum
    property xx : aa -- to be sorted in place
    property xxl : count my xx
    property yy : {}
    property cmp : cmp_
    on merge(p, q, r)
    property xx: source list
    integer p, q, r : absolute indices to specify range to be merged such that
    xx's items p thru r is the target range,
    xx's items p thru (q-1) is the first sublist,
    xx's items q thru r is the second sublist.
    (p < q <= r)
    local i, j, k, xp, xr, yi, yj, ix, jx
    if r - p = 1 then
    set xp to my xx's item p
    set xr to my xx's item r
    if my cmp(xp, xr) then
    set my xx's item p to xr
    set my xx's item r to xp
    end if
    return -- exit
    else
    if p < q - 1 then merge(p, (p + q) div 2, q - 1)
    merge(q, (q + r + 1) div 2, r)
    end if
    At this point, sublits xx[p, q-1] and xx[q, r] have been already sorted (p < q <= r)
    if my cmp(my xx's item (q - 1), my xx's item q) then
    else -- xx[p, q-1] & xx[q, r] are already sorted
    return
    end if
    set yy to my xx's items p thru r -- working copy for comparison
    set ix to q - p
    set jx to r - p + 1
    set i to 1
    set j to q - p + 1
    set k to p
    set yi to my yy's item i
    set yj to my yy's item j
    repeat
    if my cmp(yi, yj) then
    set my xx's item k to yj
    set j to j + 1
    set k to k + 1
    if j > jx then
    set my xx's item k to yi
    set i to i + 1
    set k to k + 1
    repeat until k > r
    set my xx's item k to my yy's item i
    set i to i + 1
    set k to k + 1
    end repeat
    return
    end if
    set yj to my yy's item j
    else
    set my xx's item k to yi
    set i to i + 1
    set k to k + 1
    if i > ix then
    set my xx's item k to yj
    set j to j + 1
    set k to k + 1
    repeat until k > r
    set my xx's item k to my yy's item j
    set j to j + 1
    set k to k + 1
    end repeat
    return
    end if
    set yi to my yy's item i
    end if
    end repeat
    end merge
    on cmp(x, y)
    (* primary comparator *)
    return x > y
    end cmp
    local d, i, j
    if xxl ≤ 1 then return
    if cmp_ = {} then set my cmp to cmp -- comparator fallback
    my merge(1, (xxl + 1) div 2, xxl)
    end script
    tell o to run
    end msort
    on uniq(eq_, aa, {dup:dup}) -- v0.21
    handler eq_ : comparator eq_(x, y) that returns true iff x and y are considered equal
    list aa : pre-sorted list
    (precisely, a list organized such that any duplicate items are adjacent to each other)
    boolean _dup : option whether return unique items or duplicate items
    return duplicate if true, unique otherwise.
    script o
    property parent : {} -- limit closure to minimum
    property xx : aa
    property yy : {}
    property eq : eq_
    on eq(x, y)
    (* primitive comparator *)
    x = y
    end eq
    if eq_ = {} then set my eq to my eq -- comparator fallback
    local t, x, _on
    if (count my xx) < 2 then return my xx's contents
    if _dup then
    set _on to false
    set t to my xx's item 1
    repeat with i from 2 to count my xx
    set x to my xx's item i
    if eq(x, t) then
    set end of my yy to t
    set _on to true
    else if _on then
    set end of my yy to t
    set _on to false
    end if
    set t to x
    end repeat
    if _on then set end of my yy to x
    return my yy's contents -- return duplicate elements
    else
    set t to my xx's item 1
    set end of my yy to t
    repeat with i from 2 to count my xx
    set x to my xx's item i
    if eq(x, t) then
    else
    set end of my yy to x
    set t to x
    end if
    end repeat
    return my yy's contents -- return uinque elements
    end if
    end script
    tell o to run
    end uniq
    --END OF SCRIPT2
    In order to apply it to your current Address Book problem, replace the main() handler with something like the following one.
    --SCRIPT2a (part)
    on main()
    script o
    -- input data
    property xx : {} -- list of parent; given later
    property yy : {} -- list of children per parent; given later
    -- work list
    property pp : {} -- list of children tagged by parent; i.e, lits of {child, parent}
    property qq : {}
    property rr : {}
    -- (0) get input data from AB
    tell application "Address Book"
    tell people
    set xx to its id
    set yy to its every email's value
    end tell
    end tell
    -- (1) build list of children tagged by parent *)
    (* omitted (same as the previous) *)
    -- (2) sort tagged list by child as key
    (* omitted (same as the previous) *)
    -- (3) retrieve parents with duplicate child
    (* omitted (same as the previous) *)
    -- (4) group the retrieved people in AB
    tell application "Address Book"
    repeat with r in my rr
    add person id r to group "duplicate email"
    end repeat
    end tell
    end script
    tell o to run
    end main
    --END OF SCRIPT2a
    Good luck,
    Hiroto
    Message was edited by: Hiroto

Maybe you are looking for

  • Custome Partner Function from SD to CO-PA

    Hi, I have created 3 custom partner functions and have assinged in customer master. I need these 3 custom partner function to be transfered to CO-PA during billing. Is there a easy way around to achieve this, coz there are some SAP notes which are so

  • Customized barcode option are available in Livecycle Desginer ES

    Hi all, I am new to using Adobe Livecycle Designer ES 8.2. Issue: In Adobe output designer customized the barcode options is available. If I want to change the black and white barcode lines, I have modified the "Config file" in Adobe output designer.

  • Run batch files through java code

    Hi All I need to run a batch file using java code . I am not getting any error, but also no output. Can someone let me know the problem with my code.The code i am using is import java.io.*; public class batchtest {      public static void main(String

  • Unable to send a picture via text messaging

    How can I send a photo via texting?

  • Using ByteBuffer from java.nio package

    Hi, I have a java.nio.ByteBuffer object that is returned from the C++ code, created using NewDirectByteBuffer. I would like to use this ByteBuffer object in my java code to create a WritableRaster object. I would like to avoid an array copy here as t