0

I have the following code, which works but the dynamic spacing seems pretty cluegy. Is there a more direct approach?

public class BubbleSort{
    static int[] unsorted = new int[10];
    public static void main(String[] args)throws InterruptedException{
          clearScreen();        
          
          for(int i = 0; i < 10; i++){
              unsorted[i] = (int) (Math.random() * 100);
          }
          
          printArray();
          Thread.sleep(3000);
          int x = 0;
          String space=" ";
          
          
          for (int i = 0; i < unsorted.length - 1; i++){
              for(int j = 0; j < unsorted.length - 1 - i; j++){
                  
                  if(unsorted[j] > unsorted[j+1]){
                      int temp = unsorted[j];
                      unsorted[j] = unsorted[j+1];
                      unsorted[j+1] = temp;                                            
                  }
                  if(x == 0) System.out.printf("\n" + "%2d  %2d\n",j,(j+1));
                  else System.out.printf("\n%" +x + "s%2d  %2d\n",space,j,(j+1));
                  x+=4;
                  if(x > 34)x = 0;
                  printArray();
                  Thread.sleep(1000);
                  System.out.println();
              }              
          }
    }
}
       
1

1 Answer 1

1

You could create the "spacer" dynamically, instead of printing a fixed-length spacer with offset. So instead of

if(x == 0) System.out.printf("\n" + "%2d  %2d\n",j,(j+1));
else System.out.printf("\n%" +x + "s%2d  %2d\n",space,j,(j+1));

do this:

System.out.printf("%n%s%2d  %2d%n", space.repeat(x), j, (j + 1));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.