Selection Sorting a text array
I have to use selection sort to sort out a list of names and respective ages from a notepad file.
I have been able to implement the names and ages into array, and sort the names, but not the ages if there is a plural of the name and put a comma in between.
Please can you help me - my code is below.
Code Java:
import java.io.*;
import java.util.*;
public class MultipleKeySorting {
public static void main(String[] args) throws IOException {
FileInputStream in = new FileInputStream("names_Age.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int maxIndx = -1;
String a[] = new String[12];
for (int h = 0; h < a.length-1; h++) {
maxIndx++;
a[maxIndx] = br.readLine();
System.out.println(a[maxIndx]);
}
sort(a);
System.out.println("");
print(a);
}
static String[] sort(String[] a) {
String min;
int minIndex;
for (int i = 0; i < a.length; ++i) {
min = a[i];
minIndex = i;
for (int j = i + 1; j < a.length-1; j++) { //Find minimum
if (min.charAt(0) > a[j].charAt(0)) {
min = a[j];
minIndex = j;
}
}
a[minIndex] = a[i]; //swap
a[i] = min;
}
return a;
}
public static void print(String[] a) {
// prints the elements of the specified array in sequence.
if (a == null || a.length == 0) return;
for (int i = 0; i < a.length-1; i++)
System.out.println(a[i] + ", ");
}
}
Re: Selection Sorting a text array
Without knowing the contents of the file its hard to say what is going on.
Re: Selection Sorting a text array
The data in the notepad is:
Jones 14
Abrams 15
Smith 19
Jones 9
Alexander 22
Smith 20
Smith 17
Tippurt 42
Jones 2
Herkman 12
Jones 11
The output should be:
Abrams, 15
Alexander, 22
Herkman, 12
Jones, 2
Jones, 9
Jones, 11
Jones, 14
Smith, 17
Smith, 19
Smith, 20
Tippurt, 42
Re: Selection Sorting a text array
Check the size of your array versus the number of input lines/names, if the input lines is less than the size of the array the last few elements of the array will never be set (eg their value will be null).
Re: Selection Sorting a text array
Thanks, but I think that my array size is fine - it's just that I don't know how to sort the ages out and put the comma in between the name and age of each line.
Re: Selection Sorting a text array
Quote:
Originally Posted by
ComputerSaysNo
Thanks, but I think that my array size is fine - it's just that I don't know how to sort the ages out and put the comma in between the name and age of each line.
Double check...I only count 11 entries in the file, yet you allocate an array size of 12.