/* ******************************************************************** * module: Sorts.java * auteur: Lewis and Loftus * destroyer: felipe IFT1010 * * version de la classe de Lewis et Loftus etendue * au tri a bulle * ********************************************************************/ public class Sorts { private static void swap(int [] t, int i, int j) { int temp = t[i]; t[i] = t[j]; t[j] = temp; } //----------------------------------------------------------------- // Sorts the specified array of integers using the bubble sort // algorithm. //----------------------------------------------------------------- public static void bubbleSort (int[] numbers) { // indique si une permutation a ete faite lors du dernier passage boolean bubble = true; // a chaque passage on decremente fin de 1 int fin = numbers.length-1; while (bubble) { bubble = false; // pas de permutation faite pour le moment for (int i=0; i numbers[i+1]) { bubble = true; swap(numbers,i,i+1); } fin--; } } //----------------------------------------------------------------- // Sorts the specified array of integers using the selection // sort algorithm. //----------------------------------------------------------------- public static void selectionSort (int[] numbers) { int min, temp; for (int index = 0; index < numbers.length-1; index++) { min = index; for (int scan = index+1; scan < numbers.length; scan++) if (numbers[scan] < numbers[min]) min = scan; // Swap the values swap(numbers,min,index); } } //----------------------------------------------------------------- // Sorts the specified array of integers using the insertion // sort algorithm. //----------------------------------------------------------------- public static void insertionSort (int[] numbers) { for (int index = 1; index < numbers.length; index++) { int key = numbers[index]; int position = index; // shift larger values to the right while (position > 0 && numbers[position-1] > key) { numbers[position] = numbers[position-1]; position--; } numbers[position] = key; } } //----------------------------------------------------------------- // Sorts the specified array of objects using the insertion // sort algorithm. //----------------------------------------------------------------- public static void insertionSort (Comparable[] objects) { for (int index = 1; index < objects.length; index++) { Comparable key = objects[index]; int position = index; // shift larger values to the right while (position > 0 && objects[position-1].compareTo(key) > 0) { objects[position] = objects[position-1]; position--; } objects[position] = key; } } }