Skip to content

Commit eae08e4

Browse files
authored
bubblesort
1 parent d6c7ffd commit eae08e4

File tree

1 file changed

+35
-34
lines changed

1 file changed

+35
-34
lines changed

bubblesort.java

+35-34
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,35 @@
1-
package Sorting;
2-
3-
public class bubblesort {
4-
5-
public static void main(String args[])
6-
{
7-
int a[]={3,4,5,2,1,87,45};
8-
9-
10-
for(int i=1;i<a.length;i++)
11-
{
12-
int key=a[i];
13-
14-
int hole=i-1;
15-
16-
17-
while (hole>=0 && a[hole]>key)
18-
{
19-
a[hole+1]=a[hole];
20-
hole=hole-1;
21-
22-
a[hole+1]=key;
23-
}
24-
25-
}
26-
27-
for(int i=0;i<a.length;i++)
28-
{
29-
System.out.println((a[i]));
30-
}
31-
32-
33-
}
34-
}
1+
public class BubbleSortExample {
2+
static void bubbleSort(int[] arr) {
3+
int n = arr.length;
4+
int temp = 0;
5+
for(int i=0; i < n; i++){
6+
for(int j=1; j < (n-i); j++){
7+
if(arr[j-1] > arr[j]){
8+
//swap elements
9+
temp = arr[j-1];
10+
arr[j-1] = arr[j];
11+
arr[j] = temp;
12+
}
13+
14+
}
15+
}
16+
17+
}
18+
public static void main(String[] args) {
19+
int arr[] ={3,60,35,2,45,320,5};
20+
21+
System.out.println("Array Before Bubble Sort");
22+
for(int i=0; i < arr.length; i++){
23+
System.out.print(arr[i] + " ");
24+
}
25+
System.out.println();
26+
27+
bubbleSort(arr);//sorting array elements using bubble sort
28+
29+
System.out.println("Array After Bubble Sort");
30+
for(int i=0; i < arr.length; i++){
31+
System.out.print(arr[i] + " ");
32+
}
33+
34+
}
35+
}

0 commit comments

Comments
 (0)