Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class Main {
- public static void main(String[] args) {
- int[] arr = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
- System.out.println("Before:");
- System.out.println(Arrays.toString(arr));
- int forLoopCounter = 0;
- // Optimization: reduce the inner loop range on each pass
- for (int j = 0; j < arr.length; j++) {
- for (int i = 0; i < arr.length - 1 - j; i++) { // Changed this line
- forLoopCounter++;
- if (arr[i] > arr[i + 1]) {
- int temp = arr[i];
- forLoopCounter++;
- 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));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment