Skip to content

Commit db4dfeb

Browse files
authored
Merge pull request kothariji#160 from nutanaarohi123/BubbleSort
Added Java code for Bubble Sorting
2 parents f0f54f6 + 67fb6bf commit db4dfeb

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Sorting/BubbleSort.java

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Java Code to illustate Optimized Bubble Sorting
2+
3+
import java.util.*;
4+
import java.io.*;
5+
6+
public class BubbleSort{
7+
8+
public static void main(String args[]){
9+
//Declarartion of required variables
10+
int size,temp;
11+
Scanner sc=new Scanner(System.in);
12+
int c=0;
13+
//Reading Input
14+
System.out.println("Input :\n");
15+
System.out.println("Enter the size of an array : \n");
16+
size=sc.nextInt();
17+
sc.nextLine();
18+
int arr[]=new int[size];
19+
System.out.println("Enter the elements of an array :\n");
20+
for(int index = 0; index < size; index++) {
21+
arr[index]=sc.nextInt();
22+
}
23+
//Outer Loop
24+
for (int index = 0; index < size; index++) {
25+
//Inner Loop
26+
for (int j = 0; j < size - 1 - index; j++) {
27+
//Checking if the adjacent element is larger
28+
if (arr[j] > arr[j + 1]) {
29+
//Swapping the elements, temp is used to store the temporary variable
30+
temp = arr[j];
31+
arr[j] = arr[j + 1];
32+
arr[j + 1] = temp;
33+
c++;
34+
}
35+
}
36+
if(c<1){
37+
break;
38+
}
39+
}
40+
41+
42+
//Displaying Output
43+
System.out.println("Output :\n");
44+
System.out.println("The sorted array is :\n");
45+
for (int index = 0; index < size; index++) {
46+
System.out.print(arr[index]+" ");
47+
}
48+
49+
}
50+
}
51+
52+
/*
53+
Input:
54+
Enter the size of an array: 5
55+
Enter the elements of an array :
56+
7 9 8 2 4
57+
Output :
58+
2 4 7 8 9
59+
Time Complexity :O(n)
60+
Space Complexity :O(1)
61+
*/

0 commit comments

Comments
 (0)