The full project is to take data in from a file which is a text file containing a list of all 201 countries and their respective rates of internet use in alphabetical order. Here is an example
Afghanistan 7
Albania 63
Algeria 20
Andorra 97
Angola 23
...
With this we have to Shellsort (specifically) the data numerically. I have successfully done this but I only am outputting a list of the percentages, where as I need the countries listed as well. Here is my code:
import java.io.*;
import java.util.*;
public class InternetUsers {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
String populationString = "";
String[] line = new String[201];
int populations[] = new int[201];
Scanner fileIN = new Scanner(new File("F:/CountrySortedAlpha.txt"));
while(fileIN.hasNext()){
for(int i = 0; i < 201; i++){
populationString = fileIN.nextLine().substring(26, 29);
populations[i] = Integer.parseInt(populationString.trim());
}
int j;
for(int gap = populations.length / 2; gap > 0; gap /= 2){
for (int k = 0; k < populations.length; k++){
}
for (int t = gap; t < populations.length; t++){
int tmp = populations[t];
for(j = t; j >= gap && (tmp < populations[j - gap]); j -= gap){
populations[j] = populations[j - gap];
}
populations[j] = tmp;
}
}
System.out.println("\nFinal sorted order: ");
for(int k = 0; k < populations.length; k++){
System.out.print(populations[k]);
System.out.println("");
}
System.out.println();
}
}
}
So my question is how am I to go about outputting the countries as well? do I need to completely redo the way I sorted? Here is my sample output:
Final sorted order:
1
1
2
2
2
2
2
3
....
When you parse the file, you need to store parsed value in a dictionary or some other structure. After you sort, when printing, read the values from dictionary.
I modified you code to store values in a dictionary, and added comments to the lines I added/modified. I did not touch your sorting algo, so you are still sorting on the same array:
Unless prof. said specifically do it with an array of Strings for the countries and an array of ints for the rates, @ScaryWombat's idea of an array of objects each containing a String and an int is the way to go.
That being said, you could still do it with the separate arrays if you must. Just be sure to swap both the
line
and thepopulation
entries when your sort algorithm calls for a swap, not only thepopulation
entry.