package com.basic.sorting;
public class BubbleSortingExample {
static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i ) {
System.out.print(arr[i] " ");
}
System.out.println();
}
@SuppressWarnings("unused")
static void sortingArray(int[] arr, int n) {
for (int i = 0; i < n - 1; i ) {
int flag = 0;
for (int j = 0; j < n - i - 1; j ) {
if (arr[j] > arr[j 1]) {
int temp = arr[j];
arr[j] = arr[j 1];
arr[j 1] = temp;
flag = 1;
}
}
if (flag == 0)
System.out.println("Array Sorted Already");
break;
}
}
public static void main(String[] args) {
int[] input = { 5, 1, 4, 2, 8 };
int n = input.length;
sortingArray(input, n);
System.out.println("After sorting");
printArray(input);
}
}
result with above code like
After sorting
1 4 2 5 8
But the expected is
1 2 4 5 8
CodePudding user response:
The break statement that appears at the end of the if (flag == 0) block will cause the loop to exit after the first iteration, even if the array is not fully sorted
CodePudding user response:
Put the break statement inside a block so that it is only run when the condition of the if
statement is true. Also, use a boolean
variable for flag
instead.
boolean flag = false;
for (int j = 0; j < n - i - 1; j ) {
if (arr[j] > arr[j 1]) {
int temp = arr[j];
arr[j] = arr[j 1];
arr[j 1] = temp;
flag = true;
}
}
if (!flag) {
System.out.println("Array Sorted Already");
break;
}