-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSORTING_bubble_sort.java
58 lines (50 loc) · 1.44 KB
/
SORTING_bubble_sort.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
50
51
52
53
54
55
56
57
58
Sorting In Place: Yes
Stable: Yes
METHOD1: Inefficient as it always takes O(n^2) time complexity.But if array is sorted we can bring it to O(n) time complexity.
public class bubble_sort {
public static void main(String[] args) {
int arr[]={9,0,12,-1,3,6,7,3};
for(int i=0;i<arr.length-1;i++)
{
for(int j=i;j<arr.length-i-1;j++)
{
if(arr[j]>arr[j+1])
{
int temp=arr[j+1];
arr[j+1]=arr[j];
arr[j]=temp;
}
}
}
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
METHOD2: Efficient->
public class bubble_sort {
public static void main(String[] args) {
int arr[]={1,2,3,4,5};
for(int i=0;i<arr.length-1;i++)
{
boolean swapped=true;
for(int j=i;j<arr.length-i-1;j++)
{
if(arr[j]>arr[j+1])
{
int temp=arr[j+1];
arr[j+1]=arr[j];
arr[j]=temp;
swapped=false;
}
}
if(swapped==true)
break;
}
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
}
NOTE: best case of bubble sort is O(n) while worst case and average case O(n^2)[this occurs when array is reverse sorted]