-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathBubble_Sort.java
41 lines (30 loc) · 1.02 KB
/
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
// Bubble sort in Java
import java.util.Arrays;
public class Bubble_Sort {
// perform the bubble sort
static void bubbleSort(int array[]) {
int size = array.length;
// loop to access each array element
for (int i = 0; i < size - 1; i++)
// loop to compare array elements
for (int j = 0; j < size - i - 1; j++)
// compare two adjacent elements
// change > to < to sort in descending order
if (array[j] > array[j + 1]) {
// swapping occurs if elements
// are not in the intended order
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
public static void main(String args[]) {
int[] data = { -2, 45, 0, 11, -9 };
System.out.print("Before Bubble Sort: ");
System.out.println(Arrays.toString(data));
// call method using class name
Bubble_Sort.bubbleSort(data);
System.out.print("After Bubble Sort: ");
System.out.println(Arrays.toString(data));
}
}