package sorting;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class BubbleSort {
private static List<Integer> sort(List<Integer> data) {
boolean swapFlag;
do {
swapFlag = false;
for (int i = 0; i < data.size() - 1; i++) {
if (data.get(i) > data.get(i + 1)) {
int tmp = data.get(i + 1);
data.set(i + 1, data.get(i));
data.set(i, tmp);
swapFlag = true;
}
}
} while (swapFlag);
return data;
}
public static void main(String[] args) {
List<Integer> unsortedData = new ArrayList<Integer>();
int size = new Random().nextInt(100);
for (int i = 0; i < size; i++) {
unsortedData.add(new Random().nextInt(100));
}
printSort("Unsorted data :", unsortedData);
printSort("Sorted data :", sort(unsortedData));
}
private static void printSort(String message, List<Integer> data) {
System.out.println(message);
for (int item : data) {
System.out.print(item + " ");
}
System.out.println("\n");
}
}
Friday, January 19, 2018
Bubble Sort - java 1.5
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment