Your code works well for odd inputs:
9
*
***
*****
*******
*********
*******
*****
***
*
However, the output is weirdly wrong for even inputs:
8
**
****
******
********
******
****
**
If you want to improve performance (in a way that would be noticeable to benchmarks, but not to the human eye), the most important change you should make is to reduce the number of System.out.print()
calls. Each .print()
results in a system call, which would require synchronization (acquiring a lock, in case your program is multithreaded, so that the output of multiple simultaneous .print()
calls won't get interleaved with each other), as well aas context switching (putting your Java code on hold to run code in the operating system kernel). All of that overhead is huge, compared to any other change you can make to your algorithm.
Therefore, for better performance, you should create a StringBuilder
and repeatedly append the entire diamond to it, then call System.out.println()
just once per line, or, better yet, just once at the end. Here is an example that prints an hourglass shape, which is closely related to your diamond shape.