Skip to content

Commit 27d902c

Browse files
committed
Added Bubble Sort - Easy
1 parent b209256 commit 27d902c

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Easy/08_02_2020_bubble_sort.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
Time:
3+
Best = O(n), Average = O(n^2), Worst = O(n^2)
4+
Space: O(1)
5+
*/
6+
class Solution {
7+
public int[] sortArray(int[] nums) {
8+
// Assume the array is not sorted
9+
boolean isSorted = false;
10+
while (!isSorted) {
11+
isSorted = true;
12+
for (int i = 0; i < nums.length - 1; i++) {
13+
// If current number is greater than the next
14+
if (nums[i] > nums[i + 1]) {
15+
// Swap them
16+
swap(nums, i, i + 1);
17+
// If we made a swap, then let's go through one more iteration
18+
isSorted = false;
19+
}
20+
}
21+
}
22+
return nums;
23+
}
24+
public void swap(int[] array, int i, int j) {
25+
int temp = array[i];
26+
array[i] = array[j];
27+
array[j] = temp;
28+
}
29+
}

0 commit comments

Comments
 (0)