forked from abhishekdoifode1/Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubblesort.java
More file actions
41 lines (34 loc) · 1.12 KB
/
bubblesort.java
File metadata and controls
41 lines (34 loc) · 1.12 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
// Bubble Short Algorithm in java
public class BubbleSortExample
{
public static void main(String[] args)
{
Integer[] array = new Integer[] { 12, 13, 24, 10, 3, 6, 90, 70 };
bubbleSort(array, 0, array.length);
System.out.println(Arrays.toString(array));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void bubbleSort(Object[] array, int fromIndex, int toIndex)
{
Object d;
for (int i = toIndex - 1; i > fromIndex; i--)
{
boolean isSorted = true;
for (int j = fromIndex; j < i; j++)
{
//If elements in wrong order then swap them
if (((Comparable) array[j]).compareTo(array[j + 1]) > 0)
{
isSorted = false;
d = array[j + 1];
array[j + 1] = array[j];
array[j] = d;
}
}
//If no swapping then array is already sorted
if (isSorted)
break;
}
}
}
// Output: [3, 6, 10, 12, 13, 24, 70, 90]