If the import integers are 5 2 1 12 2 10 4 13 5
However, the output shows with many "0" if the arraysize is large(20 now).
Result:
Therefore, I may ask which parts go wrong and any solution to fix the null parts.
If the import integers are 5 2 1 12 2 10 4 13 5
However, the output shows with many "0" if the arraysize is large(20 now).
Result:
Therefore, I may ask which parts go wrong and any solution to fix the null parts.
By doing this in your code:
int [] array1 = new int [20];
You are saying, initialize array1 with 0 as a default value for all.
Now if you enter only 10 values, rest of the 10 values will be zero.. hence when sorted.. 0 is less than 1 it appears first..
clear?
If the zeros are your problem, than don't initialize your array with a constant value ("20", in your example).
Just change your scanning code to:
Scanner scanner = new Scanner(new File("C:/text.txt"));
ArrayList<Integer> array1 = new ArrayList<Integer>();
while(scanner.hasNextInt() ){
array1.add(scanner.nextInt());
}
Also, you will need to convert your ArratList to an int array. The following code will help (copied from : How to convert an ArrayList containing Integers to primitive int array?):
public static int[] convertArrayListToIntArray(List<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}