-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathBubble.java
49 lines (45 loc) · 1.33 KB
/
Bubble.java
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
39
40
41
42
43
44
45
46
47
48
49
import java.util.Arrays;
public class Bubble {
public static void main(String[] args) {
int[] nums={90,24,67,556,434,17,92,637,1};
bubble(nums, nums.length-1, 0);
System.out.println(Arrays.toString(nums));
}
static void BubbleSort(int[] arr){
boolean swapped;
for(int i= 0; i<arr.length;i++){
swapped = false;
// for each step max item will come at last position
for (int j = 1; j < arr.length-i; j++) {
// swap if item is smaller than previous element in the array
if(arr[j]<arr[j-1]){
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
swapped = true;
}
}
// if didn't swap for a particular value then the array is sorted no need to go further
if(!swapped){
break;
}
}
}
// Using Recursion
static void bubble(int[] arr,int i,int j){
if(i==0){
return;
}
if(i>j){
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
bubble(arr, i, j+1);
}
else{
bubble(arr, i-1, 0);
}
}
}