CS 121 Chapter Notes - Chapter 10: Sorting Algorithm, Selection Sort, Insertion Sort

128 views5 pages

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;

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers