-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
46 lines (38 loc) · 1.29 KB
/
BubbleSort.java
File metadata and controls
46 lines (38 loc) · 1.29 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
package com.pslin.algorithms.sort;
import java.text.DecimalFormat;
import java.util.Arrays;
/**
* @author plin
*/
public class BubbleSort {
public static void main(String[] args) {
int length;
if(args.length == 0) {
length = 1000;
} else {
length = Integer.parseInt(args[0]);
}
int[] numbers = ArrayUtils.createArray(length);
ArrayUtils.shuffle(numbers);
System.out.println(Arrays.toString(numbers));
double start = System.currentTimeMillis();
int count = bubblesort(numbers);
System.out.println("Time: " + (System.currentTimeMillis() - start) + " ms");
DecimalFormat df = new DecimalFormat("#,###");
System.out.println("Number of swaps: " + df.format(count));
}
private static int bubblesort(int[] numbers) {
int count = 0;
for (int i = 0; i < numbers.length; i++) {
for (int x = 1; x < numbers.length - i; x++) {
if (numbers[x - 1] > numbers[x]) {
int temp = numbers[x - 1];
numbers[x - 1] = numbers[x];
numbers[x] = temp;
count++;
}
}
}
return count;
}
}