Implement Bubble Sort Instead of using Built-in method

This commit is contained in:
Siwat Sirichai 2020-11-17 15:04:45 +07:00
parent 760af16e58
commit 6b1af4cf0c
2 changed files with 14 additions and 5 deletions

View File

@ -1,5 +1,3 @@
import java.util.Arrays;
public class HistogramDataDisplay extends DataDisplay { public class HistogramDataDisplay extends DataDisplay {
public HistogramDataDisplay(String name, Data subject) { public HistogramDataDisplay(String name, Data subject) {
@ -10,14 +8,25 @@ public class HistogramDataDisplay extends DataDisplay {
public void update() { public void update() {
System.out.println(getClass() + ": " + name); System.out.println(getClass() + ": " + name);
int[] sortedArray = super.getContent(); int[] sortedArray = super.getContent();
Arrays.sort(sortedArray); boolean isSorted = false;
while (!isSorted) {
isSorted = true;
for (int i = 0; i < sortedArray.length - 1; i++) {
if (sortedArray[i] > sortedArray[i + 1]) {
int temp = sortedArray[i];
sortedArray[i] = sortedArray[i + 1];
sortedArray[i + 1] = temp;
isSorted = false;
}
}
}
int lastVal = -1; int lastVal = -1;
for (int i : sortedArray) { for (int i : sortedArray) {
if (i == lastVal) if (i == lastVal)
System.out.print("*"); System.out.print("*");
else { else {
System.out.format("%s%d\t*",(lastVal==-1)?"":"\n", i); System.out.format("%s%d\t*", (lastVal == -1) ? "" : "\n", i);
lastVal=i; lastVal = i;
} }
} }
System.out.println(); System.out.println();