Multithreaded array sorting

Does anyone have an example program which demonstrates how to sort an array efficiently using multiple synchronized threads. I need to use 8 threads to sort an array of 64 integers for a college project and I cant seem to work out how to do it!!
Thankyou
Stuart Mortimer

Sorting with multiple threads is only efficiant if each thread run at its own processor. Because multithreading on one processor means that all threads except one is allways in a pause state. A sorting algorithm that can be used with multithreading has to be a devide and conquer algorithm. You divide the data, and let different threads handle its own part of the data. Mergesort and Quicksort are algorithms you could use, whereas boublesort, insertionsort and shellsort are not. Using multithreaded sorting for 64 elements is an overkill, but it could be interesting for a student- project. In real life you ned far more data to get an advantage of such an advanced sorting method with so much overhead.
Both mergesort and quicksort are recursive, and both call itself two times. Thouse two calls could be done simultaniously by multithreading.
Mergesort seems to be the easyest algorithm, because mergesort always devide the data in two halfs of the same size. Quicksort might perform better however. In singlethreaded sorting quicksort is faster than mergesort except when the amount of data is too big to be kept in memory. - and offcorse in the theoretical worstcase of quicksort where the performance is O(n^2), not O(n*log(n)).

Similar Messages

  • Doubt in working of Arrays.sort method. help needed !!!!

    Hello Friends,
    I am not able to understand output of Arrays.sort method. Here is the detail of problem
    I wrote one program :
    public static void main(String[] args) throws ClassNotFoundException
         Object[] a = new Object[10];
         a[0] = new String("1");
         a[1] = new String("2");
         a[2] = new String("4");
         a[3] = new String("3");
         a[4] = new String("5");
         a[5] = new String("20");
         a[6] = new String("6");
         a[7] = new String("9");
         a[8] = new String("7");
         a[9] = new String("8");
    /* Sort entire array.*/
         Arrays.sort(a);
         for (int i = 0; i < a.length; i++)
         System.out.println(a);
    and output is :
    1
    2
    20
    3
    4
    5
    6
    7
    8
    9
    Question : Does this output is correct? If yes then on which basis api sort an array? I assume output should be 1 2 3 4 5 6 7 8 9 20.
    Can here any one please explain this?
    Thanks in advance.
    Regards,
    Rajesh Rathod

    jverd wrote:
    "20" and "3" are not numbers. They are strings, and "20" < "3" is exactly the same as "BA" < "C"The above is
    ... quote 20 quote less than quote 3 quote...
    but shows up as
    ... quote 20 quote less than quote...
    Weird.

  • Structure of arrays sort

    Hi, I have a structure of arrays as follows.
    The Structure is session.cart
    my arrays are session.cart.foodname[ ]
    session.cart.comments[ ]
    session.cart.name[ ]
    session.cart.price[ ]
    All of these arrays correspond to each other, so
    session.cart.name[1] may be John, who ordered a cheeseburger
    (session.cart.foodname[1]). So i need to sort these by the persons
    name and have the other 3 arrays sort with them, so they still
    correspond to each other. Can anyone help me with this? Ive looked
    over the structsort function but cant figure out how to apply it to
    a structure of arrays. Thanks for the help.

    I would avoid using multiple arrays, which have to refer to
    each other - without really having a proper way to execute the
    plan. Structures are better for this. I created an example, which
    you might try out, and see if it fits your needs:
    <cfscript>
    session.cart.item = structnew();
    // use the name also as a key
    session.cart.item["john"]=structnew();
    session.cart.item["john"]["name"] = "john";
    session.cart.item["john"]["foodname"] = "Ribs";
    session.cart.item["john"]["price"] = "13.99";
    session.cart.item["john"]["comments"]="Johncomment";
    session.cart.item["mary"]=structnew();
    session.cart.item["mary"]["name"] = "mary";
    session.cart.item["mary"]["foodname"] = "Apple";
    session.cart.item["mary"]["price"] = "0.49";
    session.cart.item["mary"]["comments"]="Marycomment";
    session.cart.item["adam"]=structnew();
    session.cart.item["adam"]["name"] = "adam";
    session.cart.item["adam"]["foodname"] = "Cake";
    session.cart.item["adam"]["price"] = "4.99";
    session.cart.item["adam"]["comments"]="Adamcomment";
    // the following line actually does all you ever wanted.
    arrayToList() is just a bonus
    // for easy-to-understand-output in the end. More elegant
    solutions may exist. :-)
    nameList =
    arrayToList(structSort(session.cart.item,"textnocase","asc","name"));
    </cfscript>
    <cfoutput>
    <cfloop list="#nameList#" index="currentName">
    #session.cart.item[currentName].name#<BR>
    #session.cart.item[currentName].foodname#<BR>
    #session.cart.item[currentName].price#<BR>
    #session.cart.item[currentName].comments#<BR>
    <HR>
    </cfloop>
    </cfoutput>

  • Arrays.sort() issue when Numbers are a string!

    Hey guys -- here is my problem.
    I am working on a TOP TEN SCORES mechanism for a trivia game. I have read in the score and the players name from a file. SO I have 2 different arrays topScores[] and topNames[] ---
    Now if someone plays the game and has a higher score than the lowest score, they get to put their score and name in the file and replace the low score.
    HOWEVER -- I do not know how to sort topSCORES[] and then make whatever sorted changes apply also to the topNAMES[] array.
    SO I thought - HEY I will concatenate the topScores and topNames into a single String array. And then SORT! This sounded like a great idea until I realized that the following will happen:
    100 tvance (first one)
    1000 dvance (second score)
    250 danderson (third score) !!!
    See my problem? When I sort this way - it is sorting alphabetically so it will put a 1000 score before a 200-900 score! ---
    **I hope I explained this adequately -- can someone help? Is there a way to sort the topScores array and have it also change the order of the topNames array as well?

    Create a new class - HighScore, which has a highScore and a name?Yup. This technique even has a name: object-oriented programming!
    Demo:
    import java.util.*;
    public final class HighScore implements Comparable<HighScore> {
        private final int score;
        private final String name;
        public HighScore(int score, String name) {
            if (name == null)
                throw new NullPointerException();
            this.score = score;
            this.name = name;
        public int getScore() {
            return score;
        public String getName() {
            return name;
        public int compareTo(HighScore that) {
            if (this.score < that.score)
                return -1;
            else if (this.score > that.score)
                return +1;
            else
                return this.name.compareTo(that.name);
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            else if (obj instanceof HighScore) {
                HighScore that = (HighScore) obj;
                return this.score == that.score && this.name == that.name;
            } else
                return false;
        public int hashCode() {
            return score ^ name.hashCode();
        public String toString() {
            return score + " " + name;
        //demo
        public static void main(String[] args) {
            HighScore[] top = {
                new HighScore(250, "danderson"),
                new HighScore(1000, "dvance"),
                new HighScore(100, "dvance")
            Arrays.sort(top);
            for(int i=0; i<top.length; ++i) {
                System.out.println(top);
    If you are using an older version of Java (1.4 or earlier), the generics won't be
    recognized. In that case the class definition would begin:
    public final class HighScore implements Comparable {And the compareTo method would begin:
    public int compareTo(Object obj) {
        HighScore that = (HighScore) obj;Good luck!

  • Java.util.Arrays.sort for Vector

    I used the java.util.Arrays.sort to sort an array based on the method below.
                  java.util.Arrays.sort(array, 0, total, new ComparatorX());
               repaint();
                class ComparatorX implements java.util.Comparator
              public int compare( Object p1, Object p2){
                   int x1=((Point)p1).x;
                   int x2=((Point)p2).x;
                   if(x1>x2)
                                return 1;
                   if(x1>x2)
                                return -1;
                   return 0;
         }I've since changed the array to a vector. Is there anyway I can keep the comparator. Or how can I sort the vector based on the above method.

    BTW: Don't know if it's just a typing mistake, but your code contains an error:
    class ComparatorX implements java.util.Comparator     {
       public int compare( Object p1, Object p2) {
          int x1=((Point)p1).x;
          int x2=((Point)p2).x;
          if (x1>x2) {
             return 1;
          if (x1>x2) {  // Should be: if (x2 > x1) ...
             return -1;
          return 0;

  • TreeSet vs Collection.Sort / Array.sort for Strings

    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunch

    SpaceShuttle wrote:
    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunchBig-O wise, there's no difference between sorting a list of N elements or inserting them one by one in a tree-set. Both take O(n*log(n)). But both collections are not well suited for looking up string that start with a certain substring. In that case you had better use a Patricia tree (or Radix tree).
    Good luck.

  • Relate to Array.sort(), urgent help~~

    I am using a class for store the data
    then I need to sort them
    is it the vector which want to sort is needed in same class???
    because I use other file to access them~~
    The following code:
    public Test()
    Person person;
    Vector v = new Vector();
    v.add(new Person("Johnson","Fox");
    v.add(new Person("Johnson","David");
    Object[] a = v.toArray();
    Arrays.sort(a);
    public int compareTo(Object dd,Object ww)
    if (dd instanceof Person && ww instanceof Person)
    Person d = (Person) dd;
    Person w = (Person) ww;
    return w.lname.compareTo(d.lname);
    else
    return 0;
    the code doesn't work btit can compile, can anyone help me to solve it??
    thank you for your time~~

    In Person.java use the following:
    class Person
       public int compareTo(Object cmpPerson)
          if (cmpPerson instanceof Person)
             return this.lname.compareTo( ((Person)cmpPesron).lname );
          else
             return 0;
    }

  • Array.sort() question

    I've been looking at Arrays and the Comparator interface. But I don't understand the sorting results:
    import java.util.*;
    import java.io.*;
    class SearchObjArray {
         public static void main(String[] args) {
              Console con=System.console();
              if (con==null) System.exit(1);
              String[] sa={"one","two","three","four"};
              Arrays.sort(sa);          
              con.format("The sorted string:%n");          
              for(String s: sa)
                   con.format("%s ",s);
              //four,one,three,two
              con.format("%nA binary search for \"one\": one=%s%n",Arrays.binarySearch(sa,"one"));
              //one=1, as expected. The binarySearch found "one" in position 1 of the sorted array.
              ReSortComparator rs=new ReSortComparator();     
              con.format("A binary search for \"one\" using the resort comparator on the string array: one=%s%n",Arrays.binarySearch(sa,"one",rs));
              //one=-1<====WHY -1? Why is the insertion point 0?
         static class ReSortComparator implements Comparator<String> {
              public int compare(String a, String b) {
                   return b.compareTo(a);
              

    You have to search using the same ordering rules as how the array is sorted. You sorted with one set of rules (String's natural ordering) and searched with a different set of rules (the opposite ordering, as determined by your comparator). That's the same as trying to do a binary search on an unsorted array. Since one of the preconditions of binary search is that the array be sorted, it shouldn't be surprising that you get odd results.

  • Array sort with objects?

    hits = searcher.search(query);
    //java.util.Vector sortHits = new java.util.Vector ();
    int[][] sortHits = new int[hits.length()][1];
    // assign values to array
    int teller = 0;
    for (int i = 0; i < hits.length(); i++)
         Document doc = hits.doc(i);
         String absnumtxt = doc.get("absnumtxt");
         if(sAllCookies.indexOf(absnumtxt) >= 0){
              sortHits[0] = Integer.parseInt(absnumtxt);
              teller++;
              continue;
    But the method Arrays.sort(sortHits); causes a ClassCastException error. Somebody an idea to solve this?
    The structure is:
    sortHits[0][0] = 2
    sortHits[1][0] = 0
    sortHits[2][0] = 0
    sortHits[3][0] = 0
    sortHits[4][0] = 0
    sortHits[5][0] = 0

    A two-dimentional array is an array of array of something.
    Sorting a two-dimentional array requires a Comparator, because you compare uni-dimentional arrays, and arrays are not naturally comparable.
    (BTW, why declaring a two-dimentional array here? you set the second dimention length to 1... a simple array would make it, no?)

  • Arrays.sort

    Why is the Arrays.sort method defined as
    public static void sort(Object[] a)
    instead of
    public static void sort(Comparable[] a) ?

    jverd wrote:
    This way we can sort an array whose elements are all mutually comparable, even if the array itself is not declared to be of a Comparable type. I can't think of a specific use case where that would be useful, but it's the only reason I can think of for deliberately making that decision.Dear jverd, I am not sure I understand the possible case you are referring to. I tried the following code and it gives a runtime Exception.
      public class ArraysTest {
        public static void main(String argsp[]){
            Data [] dr = new Data[4];
            dr[0] = new Data(4);        dr[1] = new Data(0);
            dr[2] = new Data(8);        dr[3] = new Data(3);
            Arrays.sort(dr);
            System.out.println(dr);
    class Data{
        Integer i;
        public Data(int j){
            i = j;
        public int compareTo(Data d){
            if(i<d.i)
                return -1;
            if(i==d.i)
                return 0;
            return 1;
        @Override
        public String toString(){
            return i.toString();
    }<font color="red">
    Exception in thread "main" java.lang.ClassCastException: temp.Data cannot be cast to java.lang.Comparable
    [Ltemp.Data;@b37c60d
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.sort(Arrays.java:1079)
    </font>

  • Multidimensional Array Sort

    Please help. I am very new to java and trying to build a multidimensional array. I have two variables 1)item_name and 2)item_value. These are values that I obtain by looping through a database result set. I need to build and array that can hold these variables. Once the multidimensional array is built I need to be able to sort it by item value.
    For example I would like to do something like this:
    while (rs.next)
    array.name = item_name
    array.value = item_value
    end
    array.sort(value)
    Thanks for any help!

    Don't use a multidimensional array. Use an array of objects, where the objects are of a class that you define. It might be something as simple as class Item that just has two fields--name and value--and their getters and setters. Or maybe just getters if you want the class to be immutable.
    Have the class implement Comparable and sort on value.
    If you sometimes want to sort on value and sometimes on name, then you'll need to either define two Comparators (one for name, one for value) or make the class Comparable on whichever is the more "natural" ordering and define a Comparator for the other one.
    Either put them in an array and use one of the java.util.Arrays.sort methods to sort them, or put them in a List (java.util.LinkedList or java.util.ArrayList) and use Collections.sort to sort them.

  • Array.sort(Object[], comparator) problems

    I have been trying for days to figure out how to sort my array of geneInfo ono the field score1.
    when i try to use Arrays.sort(gInfo, new score1Comp()) it turns all of the array null.
    class score1Comp implements Comparator
    public int compare(Object o1, Object o2)
    geneInfo g1 = (geneInfo)o1;
    geneInfo g2 = (geneInfo)o2;
    // added these checkers to get rid of nullPointerException, but checked to see that most are non null
    if(g1==null&&g2==null)
    return 0;
    if(g1==null)
    return -1;
    if(g2==null)
    return 1;
    if(g1.getScore1() == g2.getScore1())
    return 0;
    else
    double temp = g1.getScore1() - g2.getScore1();
    System.out.println("score g1 - score g2: " + temp);
    System.out.println("rounded: " + (int)Math.round(temp));
    return (int)Math.round(temp);
    public boolean equals(Object obj)
    return obj.equals (this);
    }

    You have sorting your array with null to be the least on value object. For example here:
    MyObject[] objs = new MyObject[1000];
    objs[0] = new MyObject(3);
    objs[1] = new MyObject(2);
    objs[2] = new MyObject(1);
    Arrays.sort(objs, new score1Comp());Guess what the result would be? Your array would have the first 997 elements become null and the last 3 would be sorted to (1), (2), (3).
    So the cause is how your Comparator treats the null value. The solution could be to make sure your sorting array is filled correctly, or reverse the return 1/-1 for the null treatment.
    --lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Java Array Sorting

    I am having problems sorting this array in ascending and descending order. I also need to intitialize a reset button.
    Thanks! :>)
    import java.util.*;
    import java.io.*;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Combine3 extends Applet implements ItemListener
    Label lblTitle = new Label("Sorting");
    Label lblTitle2 = new Label("Please select Sort option");
    CheckboxGroup chkItems = new CheckboxGroup();
    Checkbox chkAscending = new Checkbox("Ascending)", true, chkItems);
    Checkbox chkDescending = new Checkbox("Descending)", false, chkItems);
    Checkbox chkHidden = new Checkbox("",true,chkItems);
    Button btnSort = new Button("SORT");
         TextField txtOne = new TextField("-3");
         TextField txtTwo = new TextField("0");
         TextField txtThree = new TextField("5");
         //Textfield txtFour = new Textfield("33");
         //Textfield txtFive = new Textfield("23");
         //Textfield txtSix = new Textfield("1");
         //Textfield txtSeven = new Textfield("");
         //Textfield txtEight = new Textfield("-3");
         //Textfield txtNine = new Textfield("-3");
         //Textfield txtTen = new Textfield("-3");
    public void init()
         add(lblTitle);
         add(lblTitle2);
         add (txtOne);
         add (txtTwo);
         add (txtThree);
         add(chkAscending);
         add(chkDescending);
         add(btnSort);
         setBackground(Color.cyan);
         //     add(lblDisplay);
         chkAscending.addItemListener(this);
         chkDescending.addItemListener(this);
         //btnSort.addActionListener(this);
    /* public void actionPerformed(ActionEvent e) {
         chkHidden.setState(true);
    //Executed when checkbox is selected or unselected
    public void itemStateChanged(ItemEvent e) {
         //sort in ascending order
         String strInput;
         int intArray[] = new int[3];
         //for (int x=0; x<intArray.length; x++)
              strInput = txtOne.getText();
              intArray[0] = Integer.parseInt(strInput);
              strInput = txtTwo.getText();
              intArray[1] = Integer.parseInt(strInput);
              strInput = txtThree.getText();
              intArray[2] = Integer.parseInt(strInput);
         if (chkAscending.getState() == true)
         Arrays.sort(intArray);
         // display ascending order
         //for(int i=0; i<intArray.length; i++)
              txtOne.setText(" " + intArray[0]);
              txtTwo.setText(" " + intArray[1]);
              txtThree.setText(" " + intArray[2]);
         //lblTitle2.setText("Ascending: " + i + "Value: " + intArray);
         // sort in descending order
         else if (chkDescending.getState() == true)
    for (int i=intArray.length-1; i >= 0; i--)
              for(int j=1; j <= i; j++)
                   if (intArray[j-1] < intArray[j])
              int temp = intArray[j-1];
                   intArray[j-1] = intArray[j];
                   intArray[j] = temp;
                   } // end if
    } // end for
         } // end for
         // display descending order
         for(int i=0; i<intArray.length; i++)
         lblTitle2.setText("Descending: " + i + " Value: " + intArray[i]);
    } // end else if
    } //End itemStateChanged
    } //End Class

    You might take a quick look at the following link regarding sorting arrays. The "Arrays.sort(xxx)" mechanism works well.
    http://developer.java.sun.com/developer/TechTips/1999/tt0923.html

  • Sort 2 arrays - Arrays.sort()

    I sorted Arrays.sort(arr1);
    I also sorted my second array using same method Arrays.sort(arr2);
    Now I want to sort both my arrays in to one.. How do I do this?

    public class CopyArray
      public static void main(String args[])
        int[] x = {4,2,5,1};
        int[] y = {0,-1,3,6};
        int[] combined = new int[x.length + y.length];
        System.arraycopy(x,0,combined,0,x.length);
        System.arraycopy(y,0,combined,x.length,y.length);
        java.util.Arrays.sort(combined);
        for (int i = 0; i < combined.length; i++)
          System.out.print(" " + combined);
    System.out.println();

  • Sort seq diff between rowsorter and Arrays.sort

    I am building a JTable using cols String[] array and Object[][] array.
    When I initially build the Object[][] array I sort a temp String array using Array.sort (Arrays.sort(tempstring,String.CASE_INSENSITIVE_ORDER);)then I load the Object[][] array in the resulting sequence.
    After building the table I use setAutoCreateRowSorter(true) to allow sorting on any column.
    The problem is that the two methods of sorting appear to handle special characters differently.
    Example:
    Initial sequence of array after sorting:
    co
    Compnay Info
    cust-ord
    Customer Info
    Order Header Info
    I now load the table and it appears in the same sequence
    Once I click on the table header the seq changes to:
    co
    Compnay Info
    Customer Info
    cust-ord
    Order Header Info
    I have no preference on either sequence, I would just like the results the same on both the initial load and subsequent user requested sorts.
    Thx in advance,
    BAJH

    If I do not use String.CASE_INSENSITIVE_ORDER on the Array.sort the initial sequence is:
    Compnay Info
    Customer Info
    Order Header Info
    co
    cust-ord
    Then when I click on the table header it changes to:
    co
    Compnay Info
    Customer Info
    cust-ord
    Order Header Info
    So String.CASE_INSENSITIVE_ORDER is more alike in the results.
    The only difference appears to be the special character. "-"
    So your solution is not accurate, Thx anyway...

Maybe you are looking for

  • [Solved] Epson printer driver doesn't work

    Trying to get printing from my Epson 2200.  CUPS downloaded a driver but it does not work.  I know the usb connection and printer work as they print correctly under Ubunutu 9.04.  Unfortunately, I can't find a suitable driver anywhere on the net. Thi

  • One page in my site has 3 columns but when I publish the site it shows up with 2 columns

    I set up the site with 2 columns per page, except for one page which has 3 columns. I looks right in iweb, but when I publish the site it still shows up with 2 columns like the other pages...any idea how to correct that?

  • How do i delete everything?

    I have a copy of all the apps and everything, so i'm ready to get.. Except i don't know how. Like restoring your iDevice will delete all apps and files and totally reset everything. I want to do this with my Macbook7,1. I have Lion yes, but using the

  • Why do all downloads get downloaded as a zip file?

    Recently I was asked about downloading a file as a zipped file. I clicked ok. I didnt pay much attention to it as I thought it was just for that particular file. Now everything I download downloads as a zip file. Anyone know how to fix?

  • IdeaCentre Q150 BIOS Problem

    Hello, My company purchased 5 IdeaCentre Q150's to use on a current project.    All are the same configuration (4081-6AU).   We have a custom Windows 7 64-bit image running on each of them.   To take maximum advantage of the systems, we ordered 4GB R