Radix Sort - Examining digits

Hey guys, is there a way to examine the "X" digit within an element of an array? Example:
nums[0] = 234
nums[1] = 96
nums[2] = 436
nums[3] = 150
If I wanted to find the "one's" digit in nums[0], how would I do it? We can obviously see that the digit is "4," but I need a way for the program to recognize that, and store it into a variable. Thanks in advance.

Perhaps I should clarify my problem. Here is the full briefing.
I need to use Radix Sort to order a list of positive integers. A Radix Sort makes as many passe through the list as there are digits in the largest number to be sorted. For example, if the largest integer in the list were 492, then the algorithm would make three passes through the list to sort it.
In each pass through the list, the Radix Sort algorithm sorts the numbers based on a different digit, working from the least to the most significant digit. To do this, it uses an intermediate data strucutre, ques, an array of ten queues. Each number is placed into the queu corresponding to the value of the digit being examined. For example, in the first pass the digit in the one's place is considered, so the number 345 would be enqueued into ques[5]. The number 260 would be enqueed into ques[0]. In each pass, the algorithm moves the numbers to be sorted from the list to the array of queues and then back to the list,. After the last pass, the integers are in order, from smallest to largest.
]Step 1
Taking each integer in the list in order, insert the integer into the queue corresponding to the value of the digit currently being examined. If the integer being examined does not have a digit at a given place value, 0 is assumed for that place value. For example, 95 has no digit in the hundred's place, so, when examining the hundred's digit, the algorithm would assume the value in the hundred's place is zero and enqueue 95 into ques[0].
Step 2
After all integers have been inserted into the appropriate queues, each queue is emptied in order into the array, starting with ques[0].
For example, assume that array numbs contain the integers 380, 95, 345, 382, 260, 100, and 492. The sort will take three passes, because the largest integer in the array has 3 digits.
Here is an example diagram.
Pass I   (Examines the FIRST DIGIT, AKA "one's" digit)
Nums Before Pass                                                                                 Nums After Pass
                                                           ques
[0] 380                                                     [0]   380   260   100                                [0] 380
[1] 95                                                       [1]                                                           [1] 260
[2] 345                                                     [2]   382  492                                          [2] 100
[3] 382                                                     [3]                                                           [3] 382
[4] 250                                                     [4]                                                           [4] 492
[5] 100                                                     [5]   95   345                                           [5] 95
[6] 492                                                     [6]                                                           [6] 345
                                                                 ...goes all the way to [9]That is an example of Pass I.
So my question is, how the heck do I examine only the first digit? I know how to find the maximum amount of digits, and I know how to sort it once I get them into the queues. However, I have no clue as to find out the individual one's, ten's, hundreds digit so that I can organize them into the queue. Thanks in advance.

Similar Messages

  • Radix sort using integers

    Cany anyone help me convert my code to sort using integers and maybe using a Queue?
    Thanks in advance, I appreciate it.
    import java.util.*;
    public class RadixSort{
      String[] input;
      int maxLength;
      public RadixSort(String[] sa){
        input = sa;
        maxLength = input[0].length();
        for (int i = 1; i < input.length; ++i){
          if (input.length() > maxLength){
    maxLength = input[i].length();
    public String[] sort(){
    for (int i = maxLength -1; i > -1; --i){ //begin compare from the last char
    Arrays.sort(input, new RadixComparator(i));
    return input;
    // give two or more strings as command line args
    // ex. java RadixSort vouch wacky lover love banana ananas
    public static void main(String[] args){
    RadixSort rs = new RadixSort(args);
    String[] result = rs.sort();
    for (int i = 0; i < result.length; ++i){
    System.out.println(result[i]);
    class RadixComparator implements Comparator{
    int columnNum; //start from 0
    public RadixComparator(int col){
    columnNum = col;
    public int compare(Object o1, Object o2){
    char c1, c2;
    String s1 = (String)o1;
    String s2 = (String)o2;
    int l1 = s1.length();
    int l2 = s2.length();
    if (l1 < (columnNum + 1)){ //s1 too short
    if (l2 < (columnNum + 1)){ //both too short
    return 0;
    else{
    return -1;
    else if (l2 < (columnNum + 1)){ //s2 too short
    return 1;
    else{
    c1 = s1.charAt(columnNum);
    c2 = s2.charAt(columnNum);
    return (c1 - c2);

    sort using integersIf your integer set only contains positive numbers, you could readily use radix sort for strings for
    them. You could easily convert int[] to String[] and vice versa. If your integer set is a mix of
    positives and negatives, then you would have to run radix sort twice and concatenate the
    results. One for positives, and anothe for negatives -- the latter should be a reverse
    radix sort because -1234 is larger than -5678.

  • Radix Sort Help

    Hey I'm having a really hard time understanding the coding for the radix sort, could anyone possibly post a commented version of the radix sort preferrably done reccursively please? I'd really appreciate it.. or maybe someone can try to explain this
    http://www.cs.ubc.ca/~harrison/Java/RadixSortAlgorithm.java.html

    Well I found one that is easier to understand... here it is:
    import java.lang.*;
    import java.io.*;
    public class Radix{
        private static int q[],ql[];
        static{
            q = new int[256];
            ql = new int[256];
            for(int i=0;i<q.length;q[i++] = -1);
    public static void radixSort(int[] arr){
    int i,j,k,l,np[][] = new int[arr.length][2];
    for(k=0;k<2;k++){
    for(i=0;i<arr.length;np[0]=arr[i],np[i++][1]=-1)
    if(q[j=((255<<(k<<3))&arr[i])>>(k<<3)]==-1){
    ql[j] = q[j] = i;
    else{
    ql[j] = np[ql[j]][1] = i;
    for(l=q[i=];i<q.length;q[i++]=-1){
    for(l=q[i];l!=-1;l=np[l][1]){
    arr[j++] = np[l][0];
    public static void main(String[] args){
    int i;
    int[] arr = new int[3];
    System.out.print("original: ");
    for(i=0;i<arr.length;i++){
    arr[i] = (int)(Math.random() * 1024);
    System.out.print(arr[i] + " ");
    radixSort(arr);
    System.out.print("\nsorted: ");
    for(i=0;i<arr.length;i++)
    System.out.print(arr[i] + " ");
    System.out.println("\nDone ;-)");
    the bolded part is the main part I'm having some troubles understanding... The bitshifting and the ANDing operations, I don't see how it could ever equal -1... and also the swapping of the values.
    edit: it didn't bold.. but the parts that have the bold code
    Message was edited by:
    Reiny

  • Radix Sort for Type Chars

    I have a code for sorting Radix Sort of type Interger but im not sure how to modify it to sort Characters. This is my code for type Int:
    import java.util.ArrayList;
    import java.util.Iterator;
    public class RadixSort {
        private static final int RADIX = 10;
        private ArrayList[] buckets = new ArrayList[RADIX];
        public RadixSort() {
            for( int i = 0 ; i < RADIX; i++ ) {
                buckets[i] = new ArrayList();
            clearBuckets();
        private void clearBuckets() {
            for( int i = 0 ; i < RADIX; i++ ) {
                buckets.clear();
    private boolean distribute( Integer[] array, int position ) {
    // build the divisor
    int divisor = 1;
    while( position >= 1 ) {
    divisor *= RADIX;
    position--;
    boolean done = true;
    for( int i = 0 ; i < array.length; i++ ) {
    int val = (array[i].intValue()/divisor);
    if ( val != 0 ) done = false;
    int bin = val % RADIX;
    buckets[bin].add( array[ i ] );
    return done;
    private void collect( Integer[] array ) {
    int index = 0; // next available position in array
    for( int i = 0 ; i < RADIX; i++ ) {
    Iterator<Integer> it = buckets[i].iterator();
    while( it.hasNext() ) {
    array[ index ] = it.next();
    it.remove();
    index++;
    // what happens if this removed?
    if ( index >= array.length ) return;
    public void sort( Integer[] array ) {
    clearBuckets(); // is this necessary?
    int position = 0;
    boolean done;
    do {
    done = distribute( array, position );
    position++;
    collect( array );
    } while ( !done );

    As in the maximum size of a string?
    Do you mean characters or actual byte size?

  • Radix Sort

    I need to lexicographically orginize a list of names. I looked over the internet to find comparisson methods and for what I could see the most efficient one is Radix Sort. Now, I didn't quite understood how it works and how can I use it. I'm a newbie in java so I didn't get most of the code I saw. Could you help me kinda giving me a quick example or something like on how to do it?
    Thanks in advance...

    There's a tutorial on Collections that you should read here:
    http://java.sun.com/docs/books/tutorial/collections/index.html
    And when you read that something is "the" most efficient algorithm for sorting, don't believe it. It's actually more complicated than that.

  • Radix sort help needed

    Can someone please help me with this radix sort on a dictionary (linkedList from the java utils). I am trying to pass the linkedList into an array which the java apis say that you can do with the to.Array() method but I am getting the noninformative cannot resolve symbol. Like the theory here is that one I should be able to pass a linkedList into an array and two, that I should be able to sort the list by calling the substrings(1,MAX_LENGTH) and then do a minus one on the length for the recursive call. However, this is giving me fits at this point and I don't know if I am totally off track and this will never work or if I am just not thinking it through clearly.
    Any help at all would be appreciated greatly...
    import java.util.*;
    public class radixSort
      //  radix sort using linked lists, where radixSort is not
      //  a method of the LinkeList class.
       public void radixSort(LinkedList listA)
       //*******************this is the line that's giving me fits***********************/
       java.util.LinkedList[] objArray = listA.toArray();
       final int MAX_LENGTH  =  8;    //  Strings are no more than 8 characters
       final int RADIX_SIZE = 26;    //  Alphabet has 26 letters
       // Use an array of 26 ArrayLists to groups the elements of the array
       createQueue[] groups = new createQueue[RADIX_SIZE];
       for (int x = 0; x < MAX_LENGTH; x++)
                 for (int i; i < MAX_LENGTH; i++)
                 groups = new createQueue();
              for (int position=MAX_LENGTH; position < 0; position--)
    for (int scan=0; scan < MAX_LENGTH; scan++)
    //ListIterator iter1 = listA.listIterator();
    String temp = String.valueOf (listA[scan]);
    String letter = temp.substring(0, position);
    groups[letter].enqueue ((listA[scan]));
    // gather numbers back into list
    int num = 0;
    for(int d=0; d<MAX_LENGTH; d++)
    while (!(groups[d].isEmpty()))
    numObj = groups[d].dequeue();
    listA[num] = numObj.intValue();
    num++;
    //****************************Here is the createQueue class...***********************/
    public class createQueue
    * Construct the queue.
    public createQueue( )
    front = back = null;
    * Test if the queue is logically empty.
    * @return true if empty, false otherwise.
    public boolean isEmpty( )
    return front == null;
    * Insert a new item into the queue.
    * @param x the item to insert.
    public void enqueue( Object x )
    if( isEmpty( ) ) // Make queue of one element
    back = front = new ListNode( x );
    else // Regular case
    back = back.next = new ListNode( x );
    * Return and remove the least recently inserted item
    * from the queue.
    public Object dequeue( )
    if( isEmpty( ) )
    //throw new UnderflowException( "ListQueue dequeue" );
              System.out.println("No elements");
    else;
    Object returnValue = front;
    front = front.next;
    return returnValue;
    * Get the least recently inserted item in the queue.
    * Does not alter the queue.
    public Object getFront( )
    if( isEmpty( ) )
    System.out.println("No elements");
    else;
    return front;
    * Make the queue logically empty.
    public void makeEmpty( )
    front = null;
    back = null;
    private ListNode front;
    private ListNode back;
    private void printans()
         if (isEmpty())
         System.out.println("No elements");
         else
         while (back != front)
         System.out.println (front);
         //front++;

    java.util.LinkedList[] objArray = listA.toArray();Impossible! You are going to convert a LinkedList to an array of LinkedList. It's impossible! Or, sheer nonsense, if ever possible.

  • Radix sort help again

    I created a linked list and are now trying to pass a word into a radix sort (which works outside of this particular program) so that it will sort the words and place them back into the appropriate places in the list. Just for the record, I haven't rewritten the part where it adds the sorted words back into the list so I know that part won't work right at the moment. I just need a work around for this error...
    java:197: non-static variable head cannot be referenced from a static context
    Here is the code...(does not include main cause main is long and complicated but it does work G)
    import java.util.Vector;
    public class neverishDictionary
        private Node head;
        public neverishDictionary()
             head = null;
        //begin inner node class
        private class Node
             private String word, pos, def, date, org;
             private Node next;
             public Node(String word1, String pos1, String def1, String date1, String org1)
             //1st constructor
                word = word1;
                pos = pos1;
                def = def1;
                date = date1;
                org = org1;
                next = null;
            public Node(String word1, String pos1, String def1, String date1, String org1, Node nextNode)
            //2nd constructor
                word = word1;
                pos = pos1;
                def = def1;
                date = date1;
                org = org1;
                next = nextNode;
            public String getWord()
                return word;
            public String getPos()
                return pos;
            public String getDef()
                return def;
            public String getDate()
                return date;
            public String getOrg()
                return org;
            public void setNext(Node nextNode)
                next = nextNode;
            public Node getNext()
                return next;
       }//ends the inner class
       public boolean isEmpty()
            return head == null;
       public void add(String newWord, String newPos, String newDef, String newDate, String newOrg)
            Node curr;
            Node prev;
            Node newNode = new Node (newWord, newPos, newDef, newDate, newOrg);
            if(isEmpty())
                newNode.setNext(head);
                head=newNode;
            else if(newWord.compareTo(head.getWord())<0)
                newNode.setNext(head);
                head=newNode;
            else
                prev = head;
                curr = head;
                while (curr != null)
                  if (newWord.compareTo(curr.getWord())<0)
                      prev.setNext(newNode);
                      newNode.setNext(curr);
                      break;
                   else
                       prev = curr;
                       curr = curr.getNext();
                       if (curr == null)
                           prev.setNext(newNode);
      public static Vector radixSort(Vector str1, Node prev, Node curr)
       Vector result = (Vector) str1.clone();
       final int MAX_LENGTH  =  8;    //  Strings are no more than 8 characters
       final int RADIX_SIZE = 26;    //  Alphabet has 26 letters
       int position = RADIX_SIZE;
       // Use an array of 26 ArrayLists to groups the elements of the array
        prev = null;
        curr = head;  // This is the line giving me fits and I'm not quite sure how to get around it.
        String str = curr.getWord();
       Vector[] buckets = new Vector[RADIX_SIZE];
        for (int i = 0; i < RADIX_SIZE; i++)
          buckets[i] = new Vector();
        int length = MAX_LENGTH;
        // Step through the positions from right to left, shoving into
        // buckets and then reading out again
        for (int pos = length-1; pos >=0; pos--) {
          // Put each string into the appropriate bucket
          for (int i = 0; i < MAX_LENGTH; i++) {
            str = (String) result.get(i);
            int bucketnum;
            // If the string is too short, shove it at the beginning
            if (str.length() <= pos)
              bucketnum = 0;
            else
              bucketnum = str.charAt(pos);
            buckets[bucketnum].add(str);
          // Read it back out again, clearing the buckets as we go.
          result.clear();
          for (int i = 0; i < MAX_LENGTH; i++) {
            result.addAll(buckets);
    buckets[i].clear();
    } // for(i)
    } // for(pos)
    // That's it, we're done.
    return result;
    } // sort

    Hello.
    As the error says, you are referencing a non-static member within a static function. Do a little reading on static functions. Basically you are assigning head to curr, but head has not been created yet, so the compiler is telling you it is a problem.

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

  • Help Needed: Radix Sort

    Hi,
    I am trying to implement Radix Sort algorithm in java. I want to sort some records according to Family Name then First Name. They are of different size so smaller names must be padded at the end with free spaces. They must be padded to the size of longest name.
    For example if we compare between "orange" and "apple", one free space must be added at the end of "apple" --> "apple ".
    I do not know what's the best way to figure out the name with maximum size.
    Is there any way better than iterating trough records and looking for the longest name?
    Any suggestions?
    Thanks

    Radix sort seems a pretty odd way to tackle this. However I reckon you could put the names into buckets by length, then leave the shorter ones out of the sort until you reach their last column, whereupon you put them into the pack first.

  • Need help implementing Radix sort to handle negative values

    Hi !
    I'm in desperate need for some help here...
    I've been struggling with this Radix sort algorithm for some time now. It sorts positive integers very well, and very fast, but it cant handle negative values. Is there anyone who can help me improve this algorithm to also sort negative integer values?
    I need it to be as fast or even faster then the current one, and it has to be able to sort values in an array from address x -> y.
    Here's what I have so far
    /** sorts an int array using RadixSort (can only handle positive values [0 , 2^31-1])
          * @param a an array to be sorted
          * @param b an array of the same size as a (a.length) to be used for temporary storage
          * @param start start position in a (included)
          * @param stop stop position in a (excluded)
         public void sort(int[] a, int[] b, int start, int stop){
              int[] b_orig = b;
              int rshift = 0, bits = 8;
              for (int mask = ~(-1 << bits); mask != 0; mask <<= bits, rshift += bits) {
                   int[] cntarray = null;
                   try{cntarray = new int[1 << bits];}catch(Exception e){System.out.println("Error");};
                   for (int p = start; p < stop; ++p) {
                        int key = (a[p] & mask) >> rshift;
                        ++cntarray[key];
                   for (int i = 1; i < cntarray.length; ++i)
                        cntarray[i] += cntarray[i-1];
                   for (int p = stop-1; p >= start; --p) {
                        int key = (a[p] & mask) >> rshift;
                        --cntarray[key];
                        b[cntarray[key]+start] = a[p];
                   int[] temp = b; b = a; a = temp;
              if (a == b_orig)
                   System.arraycopy(a, start, b, start, stop-start);
         }I think it can be solved by offsetting all positive values the with the number of negative values found in "a" during the last run through the main for loop (as the last (or first) 8 bits in an 32 bit integer contains the prefix bit (first bit in an 32 bit integer), 0 for positive value, 1 for negative).
    Thanks in advance !
    /Sygard.

    ah, beautiful !
    /** sorts an int array using RadixSort (can handle values [-2^31 , 2^31-1])
          * @param a an array to be sorted
          * @param b an array of the same size as a (a.length) to be used for temporary storage
          * @param start start position in a (included)
          * @param stop stop position in a (excluded)
         public void sort(int[] a, int[] b, int start, int stop){
              int[] b_orig = b;
              int rshift = 0;
              for (int mask = ~(-1 << bits); mask != 0; mask <<= bits, rshift += bits) {
                   int[] cntarray = null;
                   try{cntarray = new int[1 << bits];}catch(Exception e){System.out.println("Error");};
                   if(rshift == 24){
                        for (int p = start; p < stop; ++p) {
                             int key = ((a[p] & mask) >>> rshift) ^ 0x80;
                             ++cntarray[key];
                        for (int i = 1; i < cntarray.length; ++i)
                             cntarray[i] += cntarray[i-1];
                        for (int p = stop-1; p >= start; --p) {
                             int key = ((a[p] & mask) >>> rshift) ^ 0x80;
                             --cntarray[key];
                             b[cntarray[key]+start] = a[p];
                        int[] temp = b; b = a; a = temp;
                   else{
                        for (int p = start; p < stop; ++p) {
                             int key = (a[p] & mask) >>> rshift;
                             ++cntarray[key];
                        for (int i = 1; i < cntarray.length; ++i)
                             cntarray[i] += cntarray[i-1];
                        for (int p = stop-1; p >= start; --p) {
                             int key = (a[p] & mask) >>> rshift;
                             --cntarray[key];
                             b[cntarray[key]+start] = a[p];
                        int[] temp = b; b = a; a = temp;
              if (a == b_orig)
                   System.arraycopy(a, start, b, start, stop-start);
         }That's what I ended up with - and it works !
    Thanks a million !!

  • Having probs with radix Sort for strings

    I am creating a method that does radix sort for string values. I think I need to know the maximum value for strings to do this, and I have no Idea what that would be

    As in the maximum size of a string?
    Do you mean characters or actual byte size?

  • Hmm,. another sorting, radix sorting help

    how can i possibly code a radix sort program that shows an output in every pass?? i have search the net but almost a lot of them does have an output of already sorted array.

    skyassasin16 wrote:
    how can i possibly code a radix sort program that shows an output in every pass??By sprinkling a bunch of System.out.println's in your code.
    i have search the net but almost a lot of them does have an output of already sorted array.Then change them if the source is available.

  • Sorting of digital photos

    Hello,
    using albums within iPhoto it is possible to sort my digital photos, that's OK. What I need is a solution (with iPhoto, Aperture or another software) to sort the photos physically on the disk, I mean in a way that the filenames are changed automatically, so that I can export the files to a USB device and use them in the right order for a slideshow with external SmartTV or Beamer. I need a solution that prevents me from having to rename hundreds of files manually.
    Many thanks for any input,
    Michael.

    Simple using iPhoto - put the photos in the order you want in an album and select them - export to a desktop fodder  using the sequential naming option and view in the finder using an alpha sort  - see Exporting From iPhoto for details on export options
    LN

  • Radix sort and deletions

    Strange problem here (but YAY it compiles G)...and I think it's in the delete method but I am not a hundred percent sure...
    I have a linked list that hold 5 pieces (word, date, orig, pos, def) of data per each linked list line. I also have a vector list that just holds the word itself for all entries into the dictionary. So, the theory is that I should be able to do a radixSort (or any other sort) on the vector and take what the vector returns and create a new list from the old linked list. Does that make sense?
    My list (from a text file) looks sort of like this...
    chereba;verb;to dance;05/02;jon smith;
    semrka;verb;to speak;03/01;jim jones;
    chersl;verb;to laugh;02/01;nancy doe;
    And when I run the print command in the main menu, I get this...
    Chapter c
    chersl (verb) to laugh 02/01
    nancy doe.
    chersl (verb) to laugh 02/01
    nancy doe.
    chersl (verb) to laugh 02/01
    nancy doe.
    Chapter s
    semrka (verb) to speak 03/01
    jim jones.
    chereba (verb) to dance 05/02
    jon smith.
    I think the problem is with the remove method...I don't think that it is doing what it is supposed to do...but I could be way off my rocker and totally missing what the real problem is. Can someone please take a look at this and shove me in the right direction?
    import java.util.Vector;
    public class neverishDictionary
        private Node head;
        public neverishDictionary()
             head = null;
        //begin inner node class
        private class Node
             private String word, pos, def, date, org;
             private Node next;
             public Node(String word1, String pos1, String def1, String date1, String org1)
             //1st constructor
                word = word1;
                pos = pos1;
                def = def1;
                date = date1;
                org = org1;
                next = null;
            public Node(String word1, String pos1, String def1, String date1, String org1, Node nextNode)
            //2nd constructor
                word = word1;
                pos = pos1;
                def = def1;
                date = date1;
                org = org1;
                next = nextNode;
            public String getWord()
                return word;
            public String getPos()
                return pos;
            public String getDef()
                return def;
            public String getDate()
                return date;
            public String getOrg()
                return org;
            public void setNext(Node nextNode)
                next = nextNode;
            public Node getNext()
                return next;
       }//ends the inner class
       public boolean isEmpty()
            return head == null;
       public void addList(String newWord, String newPos, String newDef, String newDate, String newOrg)
            Node curr;
            Node prev;
            Node newNode = new Node (newWord, newPos, newDef, newDate, newOrg);
            if(isEmpty())
                newNode.setNext(head);
                head=newNode;
            else
                newNode.setNext(head);
                head=newNode;
      /*      else
                prev = head;
                curr = head;
                while (curr != null)
                  if (newWord.compareTo(curr.getWord())<0)
                      prev.setNext(newNode);
                      newNode.setNext(curr);
                      break;
                   else
                       prev = curr;
                       curr = curr.getNext();
                       if (curr == null)
                           prev.setNext(newNode);
       public void remove(String temp)
            Node prev = head;
            Node curr = head;
            int x = 0;
            while (curr != null)
            if (curr.getWord().equals(temp) && curr == head)
                      String resultWord = curr.getWord();
                      String resultPos = curr.getPos();
                      String resultDef = curr.getDef();
                      String resultDate = curr.getDate();
                      String resultOrg = curr.getOrg();
                      head = curr.getNext();
            else 
                   if (x == 0)
                      temp = curr.getWord();
                      curr = curr.getNext();
                  else if(curr.getWord().equals(temp))
                String resultWord = curr.getWord();
                      String resultPos = curr.getPos();
                      String resultDef = curr.getDef();
                      String resultDate = curr.getDate();
                      String resultOrg = curr.getOrg();
                      curr = curr.getNext();
                else
                     curr=curr.getNext();
                x++;
      public Vector radixSort(Vector vlist)
       final int NUMCHARS = 128;
      // +----------------+------------------------------------------
      // | Public Methods |
      // +----------------+
       * Sort stuff (a vector of strings) alphabetically.
        // Set up the result vector.
        Vector result = (Vector) vlist.clone();
        // Set up the buckets.
        Vector[] buckets = new Vector[NUMCHARS]; 
        for (int i = 0; i < NUMCHARS; i++) {
          buckets[i] = new Vector();
        // Determine the number of strings.
        int numStrings = vlist.size();
        // Find the length of the longest string
        int len = 0;
        for (int i = 0; i < numStrings; i++) {
          String str = (String) result.get(i);
          if (str.length() > len) len = str.length();
        } // for
        // Step through the positions from right to left, shoving into
        // buckets and then reading out again
        for (int pos = len-1; pos >=0; pos--) {
          // Put each string into the appropriate bucket
          for (int i = 0; i < numStrings; i++) {
            String str = (String) result.get(i);
            int bucketnum;
            // If the string is too short, shove it at the beginning
            if (str.length() <= pos)
              bucketnum = 0;
            else
              bucketnum = str.charAt(pos);
            buckets[bucketnum].add(str);
          // Read it back out again, clearing the buckets as we go.
          result.clear();
          for (int i = 0; i < NUMCHARS; i++) {
            result.addAll(buckets);
    buckets[i].clear();
    } // for(i)
    } // for(pos)
    putitback (result);//put the vector into the list
    // That's it, we're done.
    return result;
    } // sort
    //method to pull out the string in the vector, add the other date in it
    //and throw it back onto the list in correct sorted order.
         public void putitback(Vector result)
              String temp = " ";
              Node prev = null;
         Node curr = head;
              for (int x = 0; x < result.size(); x++)
                   temp = result.remove(x).toString();
                   if (curr.getWord().equals(temp));
                   String word = curr.getWord();
                   String pos = curr.getPos();
                   String def = curr.getDef();
                   String date = curr.getDate();
                   String org = curr.getOrg();
                   remove(temp);
                   addList(word, pos, def, date, org);
    public void displayAll()
    //radixSort(vlist);
    Node prev = head;
    Node curr = head;
    String blah = " ";
    while (curr != null)
    if (blah.compareTo(curr.getWord().substring(0,1)) < 0)
         blah = curr.getWord().substring(0,1);
         System.out.println("\nChapter " + curr.getWord().substring(0,1));
    System.out.println(curr.getWord() + " (" + curr.getPos() + ") " + curr.getDef() + " " + curr.getDate());
    System.out.println(" " + curr.getOrg() + ".");
    prev = curr;
    curr = curr.getNext();

    Why not implement the Comparable interface (int compareTo(Object) method) and let the Arrays.sort function handle the sorting?

  • Best algorithm for Sort ?

    Hi ,
    My application involves the large amount of data that needs to be sorted often. Application interacts with the other environment who is
    passing large amount of arithmetic results at run time that I need to sort and display on the screen.
    Can anybody let me know, which sort algorithm will be best suited for me ? Will it be Bubble sort/Bidirectional Bubble sort/ Quick Sort ?
    Thanks in advance.
    Warm regards,

    Radix sort is always good. Although an optimised radix sort can still only barely beat the quicksort in java.util.Array.sort. And it uses extra memory while suicksort is inmemory. However, if you want to use radix sort you can modify this piece of code to suite your type:
    public class WHATEVER{
    //rearranges the data in order
    public void radixSort(int[] data, int nrData){//We use base 16
    if(sorted) return;
    //get highest value
    int maxValue=0;
    for(int i=0; i<nrData; i++) if(data>maxValue) maxValue=data[i];
    //initial length about double the average spread
    int[][] buckets=new int[16][((nrData>>3)>0?(nrData>>3):1)];
    int length[]=new int[16];//A list with the lengths of the lists
    int digits=1;//the max digit needed to be considered
    while((1<<(digits<<2))<maxValue && digits<8) digits++;
    for(int digit=0; digit<digits; digit++){
    for(int i=0; i<16; i++) length[i]=0;
    for(int i=0; i<nrData; i++){
    int index=(data[i]>>(digit<<2))&15;//15 is a mask ...00001111
    if(length[index]>=buckets[index].length){
    buckets[index]=doubleVector(buckets[index]);
    buckets[index][length[index]++]=data[i];
    //link the lists back into data
    int index=0;
    for(int i=0; i<16; i++)
    for(int j=0; j<length[i]; j++)
    data[index++]=buckets[i][j];
    protected int[] resizeVector(int[] vector, int newSize){
    int[] newVector=new int[_newSize];
    System.arraycopy(_vector,0,newVector,0,(_vector.length<_newSize ? vector.length : newSize));
    return newVector;
    protected int[] doubleVector(int[] _vector){
    return resizeVector(_vector, _vector.length<<1);
    Gil

Maybe you are looking for

  • How to determine the structure of parameter method in WebServiceDataControl

    Hi all , I have a web Service Data Control ,this data control has web service method that take a parameter of type (java.lang.Object) how can I determine the structure of this object to send it to the web service method (how can create the object tha

  • How do I get a Metalic look to a surface?

    I'm working on making a 3D logo for a client. They've generated a 3D image in Solidworks (Two letters of text). I import it into Photoshop and convert it to a psd and then into Shake for further processing as Photoshop won't let you apply filters to

  • Audio ducking working in aperture preview but not in exported video

    I'm using a mix of stills and video and the soundtrack level ducks during the videos when in aperture, but when i export the movie, both the video clip and soundtrack audio are at 100% I've tried exporting to a few of the different presets and it mak

  • Tuxedo CICS error

    Hello, I tried to start CICS service in Tuxedo. These are the commands that I launched: [tuxedo1@afp518lx-tuxedo sample_00]$ *tmloadcf -y ${APPHOME}/config/tux/ubbconfig* CMDTUX_CAT:6652: WARN: MAXACCESSERS is not set in UBBCONFIG. Please specify an

  • Problem in create enhancement

    i want to create enhancement, i enter into include ->click on enhance(shift f4),->right click on mouse,create enhancement -. i get-"IN THIS MODE,YOU CAN CREATE IMPLEMENTATIONS ONLY" what is wrong>??????????