Reputation: 3
My program is meant to take in file in the current format with the top number being the max length of the words, the second number being the number of words that are there, and the rest being the numbers to be sorted.
4
10
437 1807 3218 1791 9058 9322 766 9977 16 7143
And then sort it so from lowest to highest. But every time i try to get it working i generally get the highest number in the first spot and the rest is just a jumbled mess. The final three for loops where meant to resemble this pseudo code:
the first power of ten = 10;
for each i up to the maximum number of digits+1
1. for each value v in the array, starting at position 0:
a. isolate the “ith” digit from v (call this digit d) – use the current power
of ten to do this
b. add v to bin[d]
2. for each bin (that is, each bin[j], starting with j=0)
a. while bin[j] is not empty
i. remove the first value from bin[j] and copy it back into the next
position in the array
3. Increase the power of ten to the next power of ten
Any help would be appreciated.
import java.io.*;
import java.util.*;
public class BinSort {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File(args[0]));
int length = sc.nextInt();
int size = sc.nextInt();
int[] temp = new int[size];
sc.nextLine();
for(int i = 0;i < temp.length;i++){
temp[i] = sc.nextInt();
}
sort(temp,size,length);
}
public static void sort(int[] input, int length,int size){
ArrayList<Integer>[]bin=(ArrayList<Integer>[]) new ArrayList[10];
for(int i = 0;i<length;i++){
bin[i] = new ArrayList<Integer>();
}
int power = 10;
for(int i = 0;i<size+1;i++){
for(int v = 0;v<input.length;v++){
int d = input[v] % power;
if(power>10)
d = d/ (power/10);
bin[d].add(input[v]);
}
for(int j = 0;j<10;j++){
while(!bin[j].isEmpty()){
int temp = bin[j].get(0);
bin[j].remove(0);
input[j] = temp;
}
}
power = power*10;
}
System.out.println("Final result");
System.out.println(Arrays.toString(input));
}
}
Upvotes: 0
Views: 71