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.
Similar Messages
-
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. -
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?
ThanksRadix 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 !! -
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. -
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. -
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 AdvanceIf 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) -
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. -
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.htmlWell 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 -
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? -
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.
-
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;
} // sortHello.
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. -
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.
Maybe you are looking for
-
Free goods are not copying in credit memo from invoice
Dear Gurus, I have made a invoice having two line items 1.normal goods with sale price and 2.free sample goods(part of promotional scheme) without any sale price. but while making credit memo for receiving goods back in cancellation of invoice , i am
-
Hi Gurus, I am trying to settle a production order to a cost center. I have already define a settlement profile with Cost center as the default reciever and assigned it to the Order type but when I tried to settle it, I have to create a distirbution
-
MacBook Pro does not go to sleep when power cord is connected
Hi Experts, I have recently discovered that my MacBook Pro (2009) with OSX Lion does not go to sleep when the power cord is connected. It does not matter if I close the lid or select sleep from the Apple menu. All that happens is that the screen is p
-
My keynote seems to be misbehaving. Me, a teacher was preparing a ppt on keynote.all of a sudden, the navigator column to my left goes black and nothing seems to move. Please help! Only 12 hours before I take class.
-
Messages.app shows phone numbers instead of names
Can anyone help me configure Messages.app to show names instead of phone numbers (for iMessage/SMS)? I'm running OS 10.10 Yosemite and my contacts are synced from iCloud. Both my phone and mac are set to the same region and language. Thanks! G