Fastest Array sort method =Flashsort?

i'm using Array.sort(object) method to sort the array but the running time is getting slower and slower as the size and number of arrays increase.
As far as i know, Java uses quicksort for Array.sort() and the running time is O(nlogn) with n is the size of the array. Even it's one of the fastest algorithm out there, it will take too long to sort a big number of array.
I heard that flashsort is the fastest algorithm with running time of O(n). This algorithm is by Dr. Karl-Dietrich Neubert's.
Anyone wrote one class already that i can use like Flashsort.sort(array a) ?

There are various implementations of this algorithm on
this page:
http://www.neubert.net/Flacodes/FLACodes.html
I haven't studied it but I had the impression that you
need to assume some things about the input data to get
O(n) time complexity; this isn't the only O(n) sorting
algorithm (radix sort is O(n) too).I think you assume nothing about data. In stead, you need more memory (20%) to sort using FlashSort.
It is kind of memory for speed sorting. Here is the java code by Roseanne Zhang if you are interested:
* FlashSort.java
* Dr. Karl-Dietrich Neubert's Flashsort1 Algorithm
* http://www.neubert.net/Flapaper/9802n.htm
* Translation of algorithm into Java by Roseanne Zhang 
* http://www.webappcabaret.com/javachina
* Timing measurement included
* Full functional application
class FlashSort
    static int   n;
    static int   m;
    static int[] a;
    static int[] l;
     * constructor
     * @param size of the array to be sorted
    public static void flashSort(int size)
        n = size;
        generateRandomArray();
        long start = System.currentTimeMillis();
        partialFlashSort();
        long mid = System.currentTimeMillis();
        insertionSort();
        long end = System.currentTimeMillis();
        // print the time result
        System.out.println("Partial flash sort time     : " + (mid - start) );
        System.out.println("Straight insertion sort time: " + (end - mid) );
     * Entry point
    public static void main(String[] args)
        int size = 0;
        if (args.length == 0)
            usage();
            System.exit(1);
        try
            size = Integer.parseInt(args[0]);
        catch (NumberFormatException nfe) {
            usage();
            System.exit(1);
        FlashSort.flashSort(size);
     * Print usage
    private static void usage()
        System.out.println();
        System.out.println("Usage: java FlashSort n ");
        System.out.println("       n is integer which is the size of array to sort");
     * Generate the random array
    private static void generateRandomArray()
        a = new int[n];
        for (int i=0; i < n; i++)
            a[i] = (int)(Math.random() * 5 * n);
        //printArray(a);
        m = n/20;
        if (m < 30) m = 30;
        l = new int[m];  
     * Partial flash sort
    private static void partialFlashSort()
        int i = 0, j = 0, k = 0;
        int anmin = a[0];
        int nmax  = 0;
        for (i=1; i < n; i++)
            if (a[i] < anmin) anmin=a;
if (a[i] > a[nmax]) nmax=i;
if (anmin == a[nmax]) return;
double c1 = ((double)m - 1)/(a[nmax] - anmin);
for (i=0; i < n; i++)
k=(int)(c1*(a[i] - anmin));
l[k]++;
//printArray(l);
for (k=1; k < m; k++)
l[k] += l[k-1];
int hold = a[nmax];
a[nmax]=a[0];
a[0]=hold;
int nmove = 0;
int flash;
j=0;
k=m-1;
while (nmove < n-1)
while (j > (l[k]-1))
j++;
k = (int)(c1 * (a[j] - anmin));
flash = a[j];
while (!(j == l[k]))
k = (int) (c1 * (flash - anmin));
hold = a[l[k]-1];
a[l[k]-1]=flash;
flash = hold;
l[k]--;
nmove++;
//printArray(a);
* Straight insertion sort
private static void insertionSort()
int i, j, hold;
for (i=a.length-3; i>=0; i--)
if (a[i+1] < a[i])
hold = a[i];
j=i;
while (a[j+1] < hold)
a[j] = a[j+1];
j++;
a[j] = hold;
//printArray(a);
* For checking sorting result and the distribution
private static void printArray(int[] ary)
for (int i=0; i < ary.length; i++) {
if ((i+1)%10 ==0)
System.out.println(ary[i]);
else
System.out.print(ary[i] + " ");
System.out.println();

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.

  • What types of sort performed by sort method of Array class ?

    I use normal bubble sort and method Array.sort() to sort some given data of an Array and then count the time.But Array.sort() method takes more time then normal bubble sort.
    Can anybody tell me what types of sort performed by sort method of Array class?

    I'm pretty sure that in eariler versions (1.2, 1.3
    maybe?) List.sort's docs said it used quicksort. Or I
    might be on crack.You are actually both correct, and wrong :)
    From the documentation of the sort methods hasn't changed in 1.2 -> 1.4 (as far as I can notice), and the documentation for sort(Object[]) says (taken from JDK 1.2 docs):
    "This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
    The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance, and can approach linear performance on nearly sorted lists."
    So, how could you be correct? The documentation for e.g. sort(int[]) (and all other primities) says:
    "Sorts the specified array of ints into ascending numerical order. The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance."
    Your memory serves you well :)
    /Kaj

  • 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.

  • Need Help with Array.sort and compare

    Hi
    I have a big problem, i try to make a java class, where i can open a file and add new words, and to sort them in a right order
    Ok everthing works fine, but i get a problem with lower and upper cases.
    So i need a comparator, i tried everything but i just dont understand it.
    How do i use this with Array.sort??
    I hope someone can help me

    Okay, you want to ignore case when sorting.
    There are two possibilities: Truly ignore case, so that any of the following are possible, and which one you'll actually get is undefined, and may vary depending on, say, which order the words are entered in the first place:
    English english German german
    english English german German
    English english german German
    english English German german
    The second possibility is that you do consider case, but it's of lower priority--it's only considered if the letters are the same. This allows only the first two orderings above.
    Either way, you need to write a comparator, and call an Arrays.sort method that takes both array and Comparator.
    The first situation is simpler. Just get an all upper or lower case copy of the strings, and then compare thosepublic int compare(Object o1, Object o2) {
        String s1 = ((String)o1).toUpper();
        String s2 = ((String)o1).toUpper();
        return s1.compareTo(s2);
    } You'll need to add your own null check if you need one.
    For the second way, your comparator will need to iterate over each pair of characters. If the characters are equal, ignoring case, then you compare them based on case. You pick whether upper is greater or less than lower.
    Of course, the need to do this assumes that such a method doesn't alrady exist. I don't know of one, but I haven't looked.

  • Array.sort Upgrade- Important - Thibault - Adobe

    Is time to upgrade the native Array Sort method, please use the news Algorithms that used in java (Novel Dual Pivot QuickSort, and Merge)
    comparing in java the sort is 10x faster than Flash, please Adobe, Thibault, upgrade this!!!! is the hearth of the data manipulation!!!

    these are user-to-user forums.
    log your request at the appropriate place: https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform

  • Sorting Methods for an Array

    I'm trying to sort an object array of bank accounts based on their balance. JGRASP doesn't like my calling statement, which I don't think is correct.
    My question is am I calling the method correctly (trying to set the bankArray[counter].getBalance()) and am I using the sort method correctly?
    my call method
    bankArray = bankArray[counter].selectionSort(bankArray[counter].getBalance(), counter);My sort method:
    public static void selectionSort (double [] sort, int length)
    for (int i = length; i < 1; i--)
    double currentMax;
    int currentMaxIndex;
    currentMax = sort[0];
    currentMaxIndex = 0;
    for (int j = 1; j < i; j++)
    if (currentMax < sort[j])
    currentMax = sort[j];
    currentMaxIndex = j;
    }//End if
    }//End for

    There are some points to notice:
    Point 1: Your method receive an array of double and an int, as you passing a double and an int.
    Point 2: Your algorithm doesn't work properly. First of all, the selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled. Also, note that you don't swap the array elements in any moment.
    Point 3: In Java, your selectionSort method don't need to receive a parameter to inform the array length. The array itself already have that information ("myArray.length").
    Point 4: About the call of your method, you made it as the selectionSort method returns an array of BankAccounts - Supposing that you represent a bank account through an BankAccount class and bankArray[i] is an array of [i]BankAccount objects. It's not true. As you can see, your selectionSort method returns void, or either, returns nothing.
    Observing those 4 first points, we can re-write your selectionSort method like this
         public static void selectionSort(double[] numbers) {
                for (int i = 0; i < numbers.length - 1; i++)
                  int minIndex = i;
                  for (int j = i + 1; j < numbers.length; j++)
                    if (numbers[j] < numbers[minIndex])
                      minIndex = j;
                  double temp = numbers;
              numbers[i] = numbers[minIndex];
              numbers[minIndex] = temp;
    Now, when I try to re-write the call, I noticed other important odd thing about your approach: The [i]selectionSort method was written to sort bankAccounts, but it receives an array of double values. Being thus, you must to previously create a double[] object filled with the accounts' balances and then sort it. But, once sorted, how can you return the balances to their proper account? There is no way to do it. You have to sort a bunch of BankAccount objects, instead of an array of balances...
    An intuitive implementation of this sorting cound be something like that:     public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
    I noticed form your call that the [i]selectionSort method boleng to the BankAccount class. Once this method is static, It's strongly recomended that you invoke this method in a static way (from the class, instead of from an object).
    Here it goes a fictional BankAccount class and a TestBankAccount class. Read it, Run it, Study it, Understand it.
    package help.sun.imbrium;
    public class BankAccount {
         private double balance;
         private int number;
         public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
         public BankAccount(int number, double balance) {
              this.balance = balance;
              this.number = number;
         public double getBalance() {
              return balance;
         public void setBalance(double balance) {
              this.balance = balance;
         public int getNumber() {
              return number;
         public void setNumber(int number) {
              this.number = number;
         public String toString(){
              return "[Account #" + number + " balance: $" + balance + "]";
    class TestBankAccount{
         public static void main(String[] args) {
              BankAccount[] accounts = {
                   new BankAccount(1, 154.23),
                   new BankAccount(2, 1554.23),
                   new BankAccount(3, 15.3),
                   new BankAccount(4, 854),
                   new BankAccount(5, -4.79),
              System.out.println("Unsorted:\n\t" + arrayToString(accounts, " "));
              BankAccount.selectionSort(accounts);
              System.out.println("Sorted:\n\t" + arrayToString(accounts, " "));
         private static String arrayToString(Object[] objs, String separator){
              StringBuilder sb = new StringBuilder();
              for (int i = 0; i < objs.length; i++) {
                   Object obj = objs[i];
                   sb.append(obj.toString());
                   if(i < objs.length - 1)
                        sb.append(separator);
              return sb.toString();

  • 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!

  • Displaying array sort swaps

    Hi there
    I have a working program that takes in the user input, puts it into an array and sorts it using two methods (bubble/selection) and prints them in ascending order. However I would like to compare the efficiency of both of these and at first I thought I would measure the amount of time it took for each sort to run. However I thought it would be more logical to display how many swaps each sort used as an easy way to compare the two together. The problem is, I have absolutely zero idea how to go about this. I have tried displaying the counts but it just isn't coming together at all. My code in full is below.
    import java.util.Scanner; // Import java library to scan user input
    public class ArraySorting { // Remember to name class the same as file name!
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int i, f, x;
            // Get Array length off user
            System.out.println("How many elements would you like to hold in an array?");
            f = sc.nextInt();
            // Create array
            int unsortedArray[];
            unsortedArray = new int[f];
            // Get array elements off user
            System.out.println("Please enter " + f + " elements into the array");
            for(x=0;x<f;x++){
           unsortedArray[x] = sc.nextInt();}
            // Sort and print Array in ascending order
            bubbleSort(unsortedArray, unsortedArray.length);
           System.out.println("The list of elements in ascending order are(BubbleSort) ");
            for(i=0; i<unsortedArray.length; i++) {
                System.out.print(unsortedArray[i] + " ");
            selectionSort(unsortedArray, unsortedArray.length);
            System.out.println(" ");
            System.out.println("The list of elements in ascending order are(SelectionSort) ");
            for(i=0; i<unsortedArray.length; i++) {
                System.out.print(unsortedArray[i] + " ");
      //   Bubble Sort algorithm
       public static void bubbleSort(int[] unsortedArray, int length)
          int temp, counter, index;
           for(counter=0; counter<length-1; counter++)
               for(index=0; index<length-1-counter; index++)
                    if(unsortedArray[index] > unsortedArray[index+1])
                       temp = unsortedArray[index];
                        unsortedArray[index] = unsortedArray[index+1];
                        unsortedArray[index+1] = temp;
       // Selection Sort algorithm
        public static void selectionSort(int[] unsortedArray, int length)
         for (int i = 0; i < unsortedArray.length - 1; i++)
              int min = i;
              for (int j = i + 1; j < unsortedArray.length; j++)
                   if (unsortedArray[j] < unsortedArray[min])
                        min = j;
              if (i != min)
                   int swap = unsortedArray;
                   unsortedArray[i] = unsortedArray[min];
                   unsortedArray[min] = swap;
    Many thanks in advance.
    Dan

    Keep a counter and increment it every time you swap. You can do that inside the sort methods and then return the value of the counter to the caller (who will then display or do something else with it).

  • 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;

  • 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?)

  • Swap Counter in simple Selection Sort method

        void sortSelection(List object)
             int swapCount=0;
               for(int i = list.length; i >= 2; i--)
                 int maxIndex = 0;
                        for(int j = 1; j < i; j++)
                             if(list[j] > list[maxIndex])
                                  maxIndex = j;
                   int temp = list[maxIndex];        //
                   list[maxIndex] = list[i-1];         //         Is the problem here?        
                   list[i-1] = temp;                     //
                   swapCount++;                     //
              System.out.println("\n" +swapCount+ " swaps were needed. ");
        }This is a pretty simple selection sort method. But I am fairly sure that I am incorrectly counting swaps with the code. I have defined a "swap" as when two array indices have their values switched. I am convinced that there is something wrong because the array of numbers is randomly generated, and yet the swapCount counter is always equal
    to (list.length-1) when it prints out. I would think it should be different every time. I indicated the line where I believe the problem lies, but I am not for sure. Thanks everybody.

    List of Random Integers, then sorted:
    9, 29, 30, 42, 53, 58, 59, 64, 66, 69, 74, 79, 79, 87, 95
    9 swaps were needed.then sort again (descending) and get this:
    95, 87, 79, 79, 74, 69, 66, 64, 59, 58, 53, 42, 30, 29, 9
    1 swaps were needed.I'm pretty sure that isn't correct. But forgive me if I did not specify that it was to work in descending order as well.
    So I tried this:
    void sortSelection(List object)
             int swapCount=0;
               for(int i = list.length; i >= 2; i--)
                 int maxIndex = 0;
                        for(int j = 1; j < i; j++)
                             if(list[j] > list[maxIndex])
                                  maxIndex = j;
                  if (maxIndex != (i-1) && ascending==true)
                       int temp = list[maxIndex];
                        list[maxIndex] = list[i-1];                             
                        list[i-1] = temp;   
                        swapCount++;
                  else if (maxIndex != (i+1) && descending==true)
                       int temp = list[maxIndex];
                        list[maxIndex] = list[i-1];                             
                        list[i-1] = temp;   
                        swapCount++;
    } adding the i+1 (because it is going in a different order)...and I think I solved it!

  • 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)).

  • 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();

Maybe you are looking for

  • Creating a view with existing GeoRaster columns and new SDO_GEOMETRY column

    Hi, In a nutshell, I already have 1 real table, which has several attributes including types such as text, numbers etc. but also a GeoRaster column. This table works great, has its metadata stored properly and is spatially indexed; no worries. I am t

  • Down payment query

    hi, Do down payment requests entered through FBA1 (Transaction type-A, Special GL indicater-F) show up in FBL5N report? I have one credit item of $1000 showing as open item in FBL5N. And if I go in BSID table it shows two open itemsof $1000, one cred

  • Finder: connecting iMac to Mac Mini server

    Hello, When I connect in the Finder to the Mac Mini Server (Snow Leopard Server), it takes on our iMac Snow Leopard 90 seconds on a fixed 1 Gbps network. Why does it take so long ? Connecting our iMac with Leopard takes only a few seconds. Thanks, Hu

  • Tablespace Freespace

    Hi All, 11.2.0.1 I got this script that produces "database freespace" report. I found this at google and it is very cool as it helps me identify when tablespace is running out of space or in "critical" condition. Obvoiusly this is for 9i since it doe

  • 2.1 EA1 - Auto Group By inserted when unwanted/expected

    I haven't tried recreating this with something a little more generic, but the following statement is incorrectly/unexpectedly adding a group by clause: SELECT Gmt_time_stamp, Scd_asof_date , submode_type_id , SELECT(NVL(MIN(d2.gmt_time_stamp),d1.mis_