Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class ArraySwapTask {
- public static void main(String[] args) {
- // Task 1.B - Array with nested loops and counters
- int[] arr = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
- System.out.println("Before:");
- System.out.println(Arrays.toString(arr));
- // Counters for tracking actions
- int forLoopCounter = 0;
- int ifStatementCounter = 0;
- // Outer loop - multiple passes through the array
- for (int j = 0; j < arr.length; j++) {
- forLoopCounter++; // Count outer loop iteration
- // Inner loop - iterate through array and swap if current > next
- for (int i = 0; i < arr.length - 1; i++) {
- forLoopCounter++; // Count inner loop iteration
- // Check if swap is needed
- ifStatementCounter++; // Count every if statement check
- if (arr[i] > arr[i + 1]) {
- // Swap positions
- int temp = arr[i];
- arr[i] = arr[i + 1];
- arr[i + 1] = temp;
- }
- }
- }
- System.out.println("After:");
- System.out.println(Arrays.toString(arr));
- System.out.println("Number of actions: " + (forLoopCounter + ifStatementCounter));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment