Question:
I want to print each number that goes into the array and simultaneously arranging it. But the ascending order does not work compared to the descending order algorithm. Of course, I could just take the ascending and descending order codes outside the for loop but it wont print one by one. It will print the whole array. How and what is the reason for this? Scanner scanner = new Scanner(System.in);
int count = 1;
int counter = 0;
int range = 0;
//range of the array validation
System.out.print(“Input no. of numbers: “);
for(int i = 0; i < 1; i++){
if(scanner.hasNextInt()){
range = scanner.nextInt();
}
else{
System.out.println("The value must not be in decimal nor a character");
break;
}
}
float[] arr = new float[range];
float[] arrTwo = new float[range];
//input validation
for(int h = 0; h < range; h++){
System.out.println(" ");
System.out.print("Input " + count + "/" + range + " numbers: ");
if(scanner.hasNextFloat()){
arr[h] = scanner.nextFloat();
arrTwo[h] = arr[h];
count++;
float temp = 0;
float tempTwo = 0;
//ascending order (does not works well)
for(int i = 0; i < range; i++){
for(int j = i + 1; j < range; j++){
if(arr[i] > arr[j]){
tempTwo = arr[i];
arr[i] = arr[j];
arr[j] = tempTwo;
}
}
}
//descending order (works well)
for(int i = 0; i < range; i++){
for(int j = i + 1; j < range; j++){
if(arrTwo[i] < arrTwo[j]){
temp = arrTwo[i];
arrTwo[i] = arrTwo[j];
arrTwo[j] = temp;
}
}
}
counter++;
//printing the ascending array
System.out.println(" ");
System.out.println("Ascending Array: ");
for(int d = 0; d < counter; d++){
System.out.print(arr[d] + " ");
}
System.out.println(" ");
//printing the descending array
System.out.println(" ");
System.out.println("Descending Array: ");
for(int d = 0; d < counter; d++){
System.out.print(arrTwo[d] + " ");
}
System.out.println(" ");
}
else{
System.out.println("This is not a number");
break;
}
}
[/code]
Answer:
This is happening because when you create an array of a primitive type, it gets prepopulated with zeroes (orfalse
if the type is boolean[]
). That affects the sorting.So suppose you input the number 5 into your array. The ascending sort moves the 5 to the end of the array (eg
[0, 0, 0, 5]
), but the descending sort leaves it at the beginning (eg [5, 0, 0, 0]
).Now when you come to print the arrays so far, and you aim to print just one element, the ascending array shows as
[0]
, but the descending one shows as [5]
.If you put negative numbers into your array, it will be the other way around – the ascending one will look “correct”, but the descending one will show 0.
If you have better answer, please add a comment about this, thank you!