-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathbubbleSort.java
More file actions
67 lines (57 loc) · 1.91 KB
/
Copy pathbubbleSort.java
File metadata and controls
67 lines (57 loc) · 1.91 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Bubble SOrt:-
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements
if they are in the wrong order.
Worst and Average Case Time Complexity: O(n*n). The worst case occurs when an array is reverse sorted.
Best Case Time Complexity: O(n). The best case occurs when an array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.
*/
//here we have sorted an array using bubble sort algorithm both in recursive and iterative way.
public class bubbleSort {
//recursive bubble sort
void bubblesort(int[] arr, int n){
//base case
if(n==1){
return;
}
for(int i = 0;i<n-1;i++){
if(arr[i]>arr[i+1]){
//swap
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
bubblesort(arr, n-1);
}
public static void main(String[] args){
int arr[] = {7,2,9,6,8,3,5,1,};
int n = arr.length;
bubbleSort ob = new bubbleSort();
ob.bubblesort(arr, n);
//print
System.out.print("Sorted array by recursion = ");
for(int i = 0;i<n;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
// Iterative bubble sort
for(int i = 0; i< n-1;i++){
for(int j = 0;j<n-i-1;j++){
if(arr[j]>arr[j+1]){
//swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
//print
System.out.print("Sorted array = ");
for(int i = 0;i<n;i++){
System.out.print(arr[i]+" ");
}
}
}
//this code is contributed by sneha-2510