-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathBubbleSort.java
55 lines (49 loc) · 1.41 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
package Sorting;
import java.util.Arrays;
/***************************************************
* Sorts a array through BubbleSort.
*
* @author https://github.com/AkMo3
*
**************************************************/
public class InsertionSort<E extends Comparable<E>> {
public static void main(String[] args) {
String[] a = {"Sachin", "Virat", "Bhuvi", "Jadeja", "Rohit", "Ashwin"};
sort(a);
System.out.println(Arrays.toString(a));
}
/**
* Main method to sort the required array.
*
* @param a - array that is to be sorted.
*/
public static void sort(Comparable[] a) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (greater(a, j)) {
swap(a, j);
}
}
}
}
/**
* Method to check whether element greater than the next.
*
* @param array - The array that is to be sorted.
* @param index - index of position that is to be compared.
*/
private static boolean greater(Comparable[] array, int index) {
return array[index].compareTo(array[index + 1]) > 0;
}
/**
* Method to swap positions of array.
*
* @param array - array in which array that is to be sorted
* @param index - index that is to be swaped
*/
private static void swap(Comparable[] array, int index) {
Comparable temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}
}