Best sorting algorithm

What would be the best sorting to algorithm for a list that is probably 90% sorted? I assume that quick sort wouldn't be the most efficient in this case.
EDIT: the list is made of strings. So i don't think any of the linear sorts will work.
Also, what sorting algorithm does Collections.sort() use?

Quote from the javadocs:
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.
http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List)

Similar Messages

  • 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

  • Hi how to find runtime for sorting algorithms

    I am new to java.......please help me out by taking a sorting algorithm and find the run time of it ......
    Thanks in Advance

    If by "runtime" you just mean the amount of time it takes to execute across some set of input...then you can use java.lang.System.currentTimeMillis() to get the current time in milliseconds since Jan 1 1970. Do that both before and after you run the code that implements the algorithm, and subtract to get the difference as running time in milliseconds. Or, if this weren't part of a homework assignment, you could just use a profiler.
    If by "runtime" you mean the execution environment, then you want to use java.lang.Runtime.getRuntime(). This has nothing to do with algorithms.
    If you mean that you want to analyze the efficiency of the algorithm (eg it's "big-O" notation), then read a textbook on algorithms. This has nothing to do with Java, apart from that Java is just one computer language out of many in which algorithms can be implemented.

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

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

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

  • Radix sort algorithm

    You guys, I need a radix sort algorithm for java. I've worked on it for a while, and I cant get it. I have this so far:
    public void radixSort(int maxDigits)
              Vector temp = new Vector();
              int count = 1;
              while(count<(Math.pow(10,maxDigits)))
                   int c=0;
                   while(c<10)
                        for(int i=0;i<students.size();i++)
                             int per = ((MyStudent)students.elementAt(i)).getPercentage()/count;                         
                             if(per%10==count)
                                  temp.add((MyStudent)students.elementAt(i));
                        c++;
                   count*=10;
              students = temp;
    students is the main vector in the class, and percentage is the thing we are trying to sort. The accessor for percentage is (MyStudent)students.elementAt(i).getPercentage(). It has to be cast to (MyStudent) object.

    Sorry here is a formatted version of my question:
    You guys, I need a radix sort algorithm for java. I've worked on it for a while, and I cant get it. I have this so far:
    public void radixSort(int maxDigits)
              Vector temp = new Vector();
              int count = 1;
              while(count<(Math.pow(10,maxDigits)))
                   int c=0;
                   while(c<10)
                        for(int i=0;i<students.size();i++)
                             int per = ((MyStudent)students.elementAt(i)).getPercentage()/count;                         
                             if(per%10==count)
                                  temp.add((MyStudent)students.elementAt(i));
                        c++;
                   count*=10;
              students = temp;
         }students is the main vector in the class, and percentage is the thing we are trying to sort. The accessor for percentage is (MyStudent)students.elementAt(i).getPercentage(). It has to be cast to (MyStudent) object.

  • Quick-Sort Algorithm HELP !!!

    hi there, I wrote a method to sort an 2D-Vector. I used the Bubble-Algorithm.
    Here the code:
    Vector == [Micky, Niko, Tete] ; [Lilo, Eli, Micha];
    public static void bubbleSort( Vector v,
    int sortColumn,
    boolean ascending )
    int i = 0,
    j = 0,
    length = v.size();
    Vector tmp1,
    tmp2;
    for (i = 0; i < (length - 1); i++)
    for (j = i+1; j < length; j++)
    tmp1 = (Vector) v.elementAt(i);
    tmp2 = (Vector) v.elementAt(j);
    if (SortUtil.isGreaterThan(tmp1.elementAt(sortColumn), tmp2.elementAt(sortColumn)) > 0)
    // swap
    SortUtil.swap2D(v, i, j);
    public class SortUtil
    public static int isGreaterThan(Object obj1, Object2)
    // String
    if ( (obj1 instanceof String) && (obj2 instanceof String) )
    return ( ((String) obj1).compareTo((String) obj2) );
    public static void swap2D(Vector v, int i)
    Vector tmp = (Vector) v.elementAt(i);
    v.setElementAt((Vector) v.elementAt(i+1), i);
    v.setElementAt(tmp, i+1);
    I want now to write a method to use the quick-sort-algorithm.
    How can I do this.
    thanks a lot.
    micky z.

    Hi
    You can use java.util.Arrays.sort() method to sort an array of data in quick sort algo. May be you will have to use a n array insted of the Vector.
    Use vector.toArray() method to get an array from the vector.
    But if you want to use a dynamically resizing container like the Vector, use a java.util.LinkedList insted of the Vector and use Collections.sort() method
    Good luck.

  • Sorting algorithm ?

    what is the sorting algorithm used in Collection.sort ?
    Its not clear what sorting algorithm is used in Collection.sort
    http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html
    Can anybody throw some light on this ?

    roy wrote:
    It works on binary search algorithm.No.
    Binary search requires that the list already be sorted. You don't use binary search to do the sorting.
    This algorithm has two forms. The first takes a List and an element to search for (the "search key"). This form assumes that the List is sorted in ascending order according to the natural ordering of its elements. The second form takes a Comparator in addition to the List and the search key.The second form also assumes the list is sorted--according to the rules of the comparator.

  • The best compression algorithm to use

    Hello Suners,
    I have a 7 GB file and i need to compress it to be 2 GB at most in order to upload it and download it faster.
    What is the best compression algorithm to use in this case? can i get the desired size and if i do how could i decompress it?

    abulseed wrote:
    OK,
    in fact it's not just a one file it's a folder containing number of files with different types the total size of them is 7GB,
    is there an algorithm can compress that folder to at most 2GB and if there one give me a link.You seem to be missing the point that it's the actual data in the files that matters for compression. A 7 GB file consisting of the words "Hello World" over and over again will compress quite significantly. A 7GB image file on the other hand will not compress hardly at all.
    Take the java.util.zip package read [http://java.sun.com/developer/technicalArticles/Programming/compression/] and try for yourself with your data. If you are hoping to compress unknown data from 7Gb to 2GB the answer is that that promise is impossible to make.

  • Sort algorithm for LARGE amount of data?

    hi,
    i need a sorting scheme for the following situation:
    I have a data file where entries are in chunks of variable length. The size of each
    chunk is defined in the first 5 bytes as a string, so the length can be from
    00001-99999, though it is usually around 1000-3000 bytes long. In reality it is never
    over 10000 bytes, but it is possible for it to be.
    Anyways, I need to sort these files according to the data found in certain
    displacements in these chunks. I will be sorting anywhere from 200,000 to
    100,000,000 at a time. Time is an issue certainly, but if it takes a week to finish that is
    fine, i just need it to work.
    So, my problem is that none of the typical sorts will work for me (bubble, heap) as far
    as i can tell because in those sorts i need to have the data loaded into memory, and
    this much data will overload the system. I have used, in the past, a c method that
    feeds these chunks to the sort function a few at a time, then makes files. Hence, not
    all chunks need to be loaded at once. Does anyone know of any solution to this
    problem? Any sort algorithms or sort classes that can handle this much data? thanks!

    Ever tried the radix sort? it's got linear complexity.
    You can still work a chunk at a time, and simply separate the data into several different "buckets", each one identified by, oh, say, the unicode number for the first character in the chunk.
    You now have several smaller lists to sort, and when you're done, NO MERGING IS NECESSARY. Simply append the lists, because the main sets of lists are already sifted into different "buckets".
    Kinda like this:
    create 256 files, and store in each every record that contains a first character that corresponds to it's ascii value. Then create 256 files for each of the original 256 files, and store in each every recond that contains a second character that correstonds to it's second character.
    etc, etc, etc.
    This is very memery intensive for storage, but in terms of run time complexity, it is linear: You will make an explicit number of passes through the list of data. And, as you go along, the lists get shorter and shorter. So while it appears that you are making 256 ^ (max length of data) passes, you're really only making (max length of data) passes, with some additional overhead of creating extra multiple files.
    For that much data, I would definitely recommend a linear algorithm. Any other sorts would be extremely slow.

  • Best Match Algorithm

    Who will explain me best match algorithm for finding an attribute value in a table

    From what you wrote I would say:
    SELECT <WhateverYouWant> FROM <WhereverItIs>
    WHERE <TheAttribute> = <TheCriterion>
    So: '=' seems to be the best match 'algorithm' you can use.
    If I misunderstood your requirement, please elaborate.

  • Best Compression algorithm ?

    which is the best compression algorithm in the world ? And wht is the compression ratio for this algo?
    namanc

    How much wood would a wood chuck chuck if a wood chuck could chuck wood?

  • Sort Algorithm Analysis

    I am currently performing analysis on many sorting algorithms. I am having a little bit of trouble and I was wondering if anyone knew of any good reference internet sites or books that could help me. Thank you.
    John

    I am actually currently using that book with some success. I was wondering if there are any internet resources that you know about. Although Weiss's analysises are extensive, I'm just trying to find different sources.
    John

  • Sort algorithm interface

    Hi all,
    As part of a project, I'm required to implement a sorting algorithm that follows a specified simple interface, which is:
    public interface Sort<T extends Comparable<T>>
         void sort(T[] array,int size);
    }The implementation of the algorithm isn't a problem (and I would be cheating if I asked for assistance with that), but I keep getting compile errors when I try to link it to the interface.
    For example:
    public class Sorting<T> implements Sort<T extends Comparable<T>>
         Sorting Algorithm
    }gives "> expected" as an error message". I've tried a few slight variations on the above, but all are giving similar errors.
    Thanks for any help in advance,
    Phil.
    Edited by: pg548 on Apr 15, 2010 6:08 AM

    pg548 wrote:
    Another question (which I'm sure is embarassingly obvious..).Well, thankfully this is New To Java.
    How do I call this sort method from somewhere else in the application?First you create your class.
    Sort<WordOccurrences> mySorter = new Sorting<WordOccurrences>();Then you call the sort method.
    mySorter.sort(wordFrequencyArray, wordFrequencyArray.length);And that's how interfaces work like magic. If you come up with a better sorter class that still follows the Sort<T> interface, you can just replace it in the "new Sorting<WordOccurrences>();" part and the code will work without further changes.

  • Quick Searches sort algorithm

    Hello,
    I'm defining some Quick Search queries to be used in Agent Inbox (through SAP Menu>Interaction Center>Administration>Agent Inbox>Define Quick Searches (CRMC_IC_AUI_QUICKS)
    There is field for defining 'Special Sort' for search results which can be used to define sort algorithm in addition to default options.
    My question is, how can I define sort algorithm? I think it is some xml algorithm but I have no idea how? Does anyone have any examples?
    Thanks,

    Hi John,
    Thanks for your response. I saw page 48 in the Inbox FAQ doc. It does talk about method for Custom sort by doesn't say anything about how?
    I need more details. Someone mentioned that we can write xml sort queries in Custom sort field but I'm looking for more information on how it can be done.
    Thanks,

  • Would this sorting algorithm work?

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

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

Maybe you are looking for