Chamara Madhushan wrote:is there any way to get this using one for loop
There is a way to do
anything with a single loop.* In the case of a bubble sort, it might not be easy to read and the execution time will still be O(n*n), but it will be technically one loop.
Just figure out what the values for the two index variables, i and j, are at the start of each iteration of the code inside the inner loop. Make just a single for() loop that has complicated initialization, condition and increment expressions to generate the same series of values for those two variables.
Specifically, the values of i and j just before you execute the inner if() are (i,j) = (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2). Can you figure out how to make a single for loop that will set i and j to those nine pairs of values?
* Arguably, everything executed on a single-threaded single-processor machine already is done in a single-loop: