-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptimizedBubbleSort.java
More file actions
40 lines (33 loc) · 1020 Bytes
/
Copy pathOptimizedBubbleSort.java
File metadata and controls
40 lines (33 loc) · 1020 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package Sorting;
import java.util.Arrays;
public class OptimizedBubbleSort {
public static void main(String[] args) {
System.out.println("case 1 : ");
int[] array = {1,2,3,4,5};
System.out.println(Arrays.toString(bubble(array)));
System.out.println("Case 2 : ");
int[] arr2 = {5,3,7,1,0,23};
System.out.println(Arrays.toString(bubble(arr2)));
}
static void swap(int[] arr , int first , int second){
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
static int[] bubble(int[] arr){
boolean swaped = false;
for (int i=0;i<arr.length-1;i++){
for(int j=0;j<arr.length-i-1;j++){
if(arr[j]>arr[j+1]){
swap(arr,j,j+1);
swaped=true;
}
}
if(!swaped) {
System.out.println("optimized solution");
break;
}
}
return arr;
}
}