-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbbleSort.java
More file actions
83 lines (46 loc) · 1.36 KB
/
Copy pathBubbbleSort.java
File metadata and controls
83 lines (46 loc) · 1.36 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.io.*;
public class BubbleSort{
public static void main(String[] args) {
int[] arr = {1,4,5,3,2};
//create two pointers
//one that points to an element and another that points to an element in front of it
//now create a boolean that is initially false
//this boolean is only true when we make a full pass of the array without swapping elements
//
//
// the outer loop should be a while loop
// the inner loop should be a for loop
//
// so while the boolean is still not false false
//
//
//run a for loop with int i = 0 then i + i, maximum is i < i - 1;;
//if the two the previous element is smaller than the next element then swap them, else increment
//
//https://www.youtube.com/watch?time_continue=1&v=nmhjrI-aW5o
//
boolean sorted = false;
while(!sorted) {
sorted = true;
for(int i = 0; i < arr.length - 1; i++) {
if(arr[i] > arr[i + 1]) {
int holder = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = holder;
sorted = false;
}
}
}
printArray(arr);
}
private static void printArray(int[] anArray) {
for (int i = 0; i < anArray.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(anArray[i]);
}
System.out.println();
System.out.println();
}
}