//-------------------------------------------------------------------- // Basic sorting algorithms //-------------------------------------------------------------------- public class Sort { public static void main (String[] args) { int[] list = {9,4,6,8,2,4,7,1}; printarray(list); bubbleSort(list); printarray(list); } public static void printarray (int[] list) { for (int index = 0; index < list.length; index++) System.out.print(list[index] + " "); System.out.println(); } public static void bubbleSort (int[] list) { boolean sorted; int temp; do { sorted = true; for (int i = 0; i < list.length-1; i++) if (list[i] > list[i+1]) { temp = list[i]; list[i] = list[i+1]; list[i+1] = temp; sorted = false; } } while (!sorted); } public static void selectionSort (int[] list) { int min, temp; for (int index = 0; index < list.length-1; index++) { min = index; for (int scan = index+1; scan < list.length; scan++) if (list[scan] < list[min]) min = scan; // Swap the values temp = list[min]; list[min] = list[index]; list[index] = temp; } } public static void insertionSort (int[] list) { for (int index = 1; index < list.length; index++) { int key = list[index]; int position = index; // Shift larger values to the right while (position > 0 && key < list[position-1]) { list[position] = list[position-1]; position--; } list[position] = key; } } }