Courses‎ > ‎AP Computer Science‎ > ‎Konstantinovich‎ > ‎notes‎ > ‎

### 2017-12-08 HW

posted Dec 8, 2017, 9:26 AM by Konstantinovich Samuel
 Goal: Bubble SortHW : Monday morning Sorts.java should have:String name()  : returns a string "PERIOD,LAST,FIRST"  e.g.  "09,Matsui,Wadsworth"  ( "09" or "10" are the periods!)void insertionSort(int[])void selectionSort(int[])void bubbleSort(int[])Time testing your sorts!The next O(n2) sort we will learn is the bubble sort.Similar to the other O(n2) sorts we learned, this runs through each element and does a linear pass on each. The bubble sort starts at the 1st element and compares adjacent elements of the array up until the end. If an adjacent pair is out of order it swaps them. Ultimately this places the largest element into the last position.The next pass, the algorithm starts at the 1st element again, except it will stop 1 element early because the largest element has been moved to the correct index after the first pass.Repeat this N times, but if no swaps have been made, stop the sort.First Pass( 5 1 4 2 8 )  ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.( 1 5 4 2 8 )  ( 1 4 5 2 8 ), Swap since 5 > 4( 1 4 5 2 8 )  ( 1 4 2 5 8 ), Swap since 5 > 2( 1 4 2 5 8 )  ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.Second Pass( 1 4 2 5 8 )  ( 1 4 2 5 8 )( 1 4 2 5 8 )  ( 1 2 4 5 8 ), Swap since 4 > 2( 1 2 4 5 8 )  ( 1 2 4 5 8 )// SKIP IT! ( 1 2 4 5 8 )  ( 1 2 4 5 8 ) //This is not a required check since you know 8 is in place.Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.Third Pass( 1 2 4 5 8 )  ( 1 2 4 5 8 ) // no swap( 1 2 4 5 8 )  ( 1 2 4 5 8 ) // no swap// SKIP IT! ( 1 2 4 5 8 )  ( 1 2 4 5 8 ) //This is not a required check since you know 5 is in place.// SKIP IT! ( 1 2 4 5 8 )  ( 1 2 4 5 8 ) //This is not a required check since you know 8 is in place.Since there have been no swaps, stop!