Wonkiest29

Untitled

Nov 14th, 2025
403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class ArraySwapTask {
  4. public static void main(String[] args) {
  5. // Task 1.B - Array with nested loops and counters
  6. int[] arr = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
  7.  
  8. System.out.println("Before:");
  9. System.out.println(Arrays.toString(arr));
  10.  
  11. // Counters for tracking actions
  12. int forLoopCounter = 0;
  13. int ifStatementCounter = 0;
  14.  
  15. // Outer loop - multiple passes through the array
  16. for (int j = 0; j < arr.length; j++) {
  17. forLoopCounter++; // Count outer loop iteration
  18.  
  19. // Inner loop - iterate through array and swap if current > next
  20. for (int i = 0; i < arr.length - 1; i++) {
  21. forLoopCounter++; // Count inner loop iteration
  22.  
  23. // Check if swap is needed
  24. ifStatementCounter++; // Count every if statement check
  25. if (arr[i] > arr[i + 1]) {
  26. // Swap positions
  27. int temp = arr[i];
  28. arr[i] = arr[i + 1];
  29. arr[i + 1] = temp;
  30. }
  31. }
  32. }
  33.  
  34. System.out.println("After:");
  35. System.out.println(Arrays.toString(arr));
  36. System.out.println("Number of actions: " + (forLoopCounter + ifStatementCounter));
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment