-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
executable file
·32 lines (26 loc) · 905 Bytes
/
Copy pathBubbleSort.java
File metadata and controls
executable file
·32 lines (26 loc) · 905 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
package com.codeWithArsalon.Algorithms;
public class BubbleSort {
// each pass next largest number moves into position (ascending order)
//O(n) * O(n) = quadratic time complexity!
//O(n) - passes (worst case)
//O(n) - comparisons
public void sort(int [] array) {
boolean isSorted; //reduce O(n) iterations if already sorted
for (var i = 0; i < array.length; i++) {
isSorted = true;
for (var j = 1; j < array.length - i; j++) {
if (array[j] < array[j - 1]) {
swap(array, j, j - 1);
isSorted = false;
}
}
if (isSorted)
return;
}
}
private void swap (int [] array, int indexOne, int indexTwo){
var temp = array [indexOne];
array[indexOne] = array[indexTwo];
array[indexTwo] = temp;
}
}