forked from lemonbashar/java-algo-expert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
40 lines (35 loc) · 951 Bytes
/
BubbleSort.java
File metadata and controls
40 lines (35 loc) · 951 Bytes
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
package algoexpert.easy;
/*
Implement Bubble Sort
-> repeatedly swap the adjacent elements if they are in wrong order
*/
public class BubbleSort {
public static void test()
{
int [] test = {5,1,4,3,2};
int [] sorted = bubbleSort(test);
for (int x: sorted) { System.out.print(x + " ");}
}
// Best - O(n)
// Average - O(n^2)
// Worst - O(n^2)
public static int[] bubbleSort(int[] array) {
if(array.length < 2) { return array; }
boolean isSorted = false;
while(!isSorted)
{
isSorted = true;
for(int i = 0; i < array.length - 1; i++)
{
if (array[i] > array[i+1])
{
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
isSorted = false;
}
}
}
return array;
}
}