I tried changing the i and j variables but it doesn't seem to work. THank you for the help. `public static void main(String[] args) {
double[] nameArray = {20.0,30.2,25.2,75.23,20.0,2.0,25.22};
double tempElement;
for (int i=0; i < nameArray.length; i )
{
// This inner loop selects and compares each remaining values to the selected element by the outer for loop.
for (int j=i 1; j < nameArray.length; j )
{
// This if loop compares the elements.
if (nameArray[i] > nameArray[j]);
{
// This if loop will only run if the next array element is smaller than
// the previous array element being compared.
// This tempElement is used for proper assigning of the variables.
tempElement = nameArray[i];
nameArray[i] = nameArray[j];
nameArray[j] = tempElement;
}
}
}
// This for loop assigns the sorted elements in the descending order to the other array.
for (int i = 0; i<nameArray.length; i )
{
System.out.println(nameArray[i]);
}
}`
CodePudding user response:
Simple mistake: Remove the ;
after the if-statement.
The semicolon after if means there is nothing to do if the if case is true.
The part in the curly brackets to swap the elements will then always be executed. That is because you can add curly brackets at any point in your code to structure it. It's not effected by the if because that statement was already ended by the semicolon.
To further explain it, you can write a perfectly fine if without any curly brackets. That means only the first following row is supposed to be included in the if statement:
if (condition)
do()
doA()
In this code do is only executed if the condition is true, doAlways() on the other hand is always executed.
Now if you change it like this:
if (condition)
do()
{
doAlways()
{
it still does exactly the same. The curly brackets don't change anything because the do not directly follow the if statement. So only the first row after is included and get's conditionally executed. doAlways() always get's executed again.
Now to change it like you had:
if (condition)
; <-- this is an empty statement
{
doAlways()
{
again only the first row after the if is affected by it. This time it's an empty statement. So basically the condition decides if you should do nothing or execute the empty statement and .. do nothing. doAlways() still get's executed regardless of the condition.
CodePudding user response:
I think you have a small problem in your sorting algorithm, the main(outside) loop needs to compare the second from last element in the array with the last one so it can deal with all the elements in your array then it should be (int i=0; i < nameArray.length-1; i )
the inside loop is good.