forked from akkupy/codeDump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbubbleSort.java
70 lines (63 loc) · 2.04 KB
/
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
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
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {5, 3, 4, 1, 2};
insertion(arr);
System.out.println(Arrays.toString(arr));
}
static void insertion(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i+1; j > 0; j--) {
if (arr[j] < arr[j-1]) {
swap(arr, j, j-1);
} else {
break;
}
}
}
}
static void selection(int[] arr) {
for (int i = 0; i < arr.length; i++) {
// find the max item in the remaining array and swap with correct index
int last = arr.length - i - 1;
int maxIndex = getMaxIndex(arr, 0, last);
swap(arr, maxIndex, last);
}
}
static void swap(int[] arr, int first, int second) {
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
static int getMaxIndex(int[] arr, int start, int end) {
int max = start;
for (int i = start; i <= end; i++) {
if (arr[max] < arr[i]) {
max = i;
}
}
return max;
}
static void bubble(int[] arr) {
boolean swapped;
// run the steps n-1 times
for (int i = 0; i < arr.length; i++) {
swapped = false;
// for each step, max item will come at the last respective index
for (int j = 1; j < arr.length - i; j++) {
// swap if the item is smaller than the previous item
if (arr[j] < arr[j-1]) {
// swap
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
swapped = true;
}
}
// if you did not swap for a particular value of i, it means the array is sorted hence stop the program
if (!swapped) { // !false = true
break;
}
}
}
}