Wonkiest29

Untitled

Nov 14th, 2025
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. int[] arr = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
  6. System.out.println("Before:");
  7. System.out.println(Arrays.toString(arr));
  8. int forLoopCounter = 0;
  9.  
  10. // Optimization: reduce the inner loop range on each pass
  11. for (int j = 0; j < arr.length; j++) {
  12. for (int i = 0; i < arr.length - 1 - j; i++) { // Changed this line
  13. forLoopCounter++;
  14. if (arr[i] > arr[i + 1]) {
  15. int temp = arr[i];
  16. forLoopCounter++;
  17. arr[i] = arr[i + 1];
  18. arr[i + 1] = temp;
  19. }
  20. }
  21. }
  22.  
  23. System.out.println("After:");
  24. System.out.println(Arrays.toString(arr));
  25. System.out.println("Number of actions: " + (forLoopCounter));
  26. }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment