-
Notifications
You must be signed in to change notification settings - Fork 1
/
BubbleSort.java
41 lines (33 loc) · 864 Bytes
/
BubbleSort.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
package algorithms.sort;
/**
* Stable sort
* time: O(n^2) Quadratic Time
* in-place Algorithm
*/
public class BubbleSort {
public static void swap(int[] arr, int i, int j) {
if (i == j) {
return;
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static int[] bubbleSort(int[] arr) {
for (int i = arr.length - 1; i > -1; i--) {
for (int j = 0; j < i; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
return arr;
}
public static void main(String[] args) {
int[] arr = {23, 43, 43, 21, 2, 4, 77, 9, 0, 788, 7};
int[] sortedArray = bubbleSort(arr);
for (int item : sortedArray) {
System.out.println(item);
}
}
}