package sorting;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
public class InsertionSort {
private static List<Integer> sort(List<Integer> data) {
List<Integer> sortedData = new LinkedList<Integer>();
outerLoop:
for (int number : data) {
for (int i = 0; i < sortedData.size(); i++) {
if (number < sortedData.get(i)) {
sortedData.add(i, number);
continue outerLoop;
}
}
sortedData.add(sortedData.size(), number);
}
return sortedData;
}
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(65536)-32768);
}
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");
}
}
Sunday, January 21, 2018
Insertion Sort
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment