This is the algorithm I'm supposed to make:
“Here is how a garden gnome sorts a line of flower pots. Basically, he looks at the flower pot next to him and the previous one; if they are in the right order he steps one pot forward, otherwise he swaps them and steps one pot backwards. If there is no previous pot, he steps forwards; if there is no pot next to him, he is done.”
So far I wrote this code:
//import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class MyProgram {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
int[] array = new int[10];
for(int i = 0; i < array.length; i++)
{
array[i] = input.nextInt();
}
input.close();
int counter = 0;
boolean nowDone = true;
do {
for(int i = 1; i < array.length; i++)
{
int str = array[i];
int newNum = i - 1;
while(newNum > -1 && array[newNum] > str)
{
array[newNum + 1] = array[newNum];
counter++;
newNum--;
}
array[newNum + 1] = str;
}
nowDone = false;
} while(nowDone = true);
System.out.println("The Gnome moved " + counter + " times to organize the pots");
}
}
For the problem, it's not stopping at the limit of 10 numbers from the user for input. One other error is that it shows an index out of bounds exception error. How would I resolve this?
Thanks