CS 121 Chapter Notes - Chapter 10: Sorting Algorithm, Selection Sort, Insertion Sort
Document Summary
// driver for testing a sorting algorithm public class phonelist { // creates an array of contact objects, sorts them, then prints them. Phonelist class: uses a selection sort to arrange a list of contact objects into. // sorts the specified array of objects using the selection sort algorithm. public static void selectionsort(comparable [] list) min = scan; if (list[scan]. compareto(list[min]) < 0) min = index; for (int scan =index+1; scan < list. length; scan++) // swap the values temp = list[min]; list[min] = list[index]; list[index] = temp; int min; Comparable temp; for (int index = 0; index < list. length-1; index++) // sorts the specified array of objects using the insertion sort algorithm. Sorting class: public static void insertionsort(comparable [] list) for (int index = 1; index < list. length; index++) Comparable key = list[index]; int position = index; // shift larger values to the right. while (position > 0 && key. compareto(list[position-1]) < 0) list[position] = list[position-1]; position--; list[position] = key;