-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3.BubbleSort using Recursions
More file actions
47 lines (37 loc) · 1.16 KB
/
3.BubbleSort using Recursions
File metadata and controls
47 lines (37 loc) · 1.16 KB
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
package sorting;
import java.util.Arrays;
public class bubbleRecursion {
static void bubbleSort(int arr[],int n) {
// base case for coming out of the recursive loop
if(n==1) {
return;
}
int count=0;
// One pass of bubble sort causes the largest
//element to move to the last position
for(int j=0;j<n-1;j++) {
if(arr[j]>arr[j+1]) {
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
count=count+1;
}
}
//outside the for loop
if(count==0) {
return;
}//for checking whether any recursion is taking place or not
//as a result of this loop the largest element is shifted to last place
//since here we are only using one for loop
//calling the function again for the remaining element of the array
// here this function calls works the task of the outer for loop in the former bubble sort algorithms
bubbleSort(arr,n-1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]= {12,32,1,14,15,76};
bubbleSort(arr,arr.length);
System.out.println("sorted array is:");
System.out.println(Arrays.toString(arr));
}
}