Presentation is loading. Please wait.

Presentation is loading. Please wait.

Selection Insertion and Merge

Similar presentations


Presentation on theme: "Selection Insertion and Merge"— Presentation transcript:

1 Selection Insertion and Merge
Sorts on the AP Exam Selection Insertion and Merge

2 Selection sort How it works Example Low High 2 6 8 3 15 1 7 Stability
Stability Speed Your turn High Low Check, mark, switch Not stable O(n2)

3 Selection Sort //a is the array name,
// nElems = the number of elements being sorted int out, in, min; int dummy; // If sorting an array of ints for(out=0; out<nElems-1; out++) // outer loop { min = out; // minimum for(in=out+1; in<nElems; in++) // inner loop if(a[in] < a[min] ) // Check if min greater, min = in; // Mark, we have a new min dummy = a[out]; //Switch a[out] = a[min]; a[min] = dummy; } // end for(out)

4 Insertion sort How it works Example Low High 8 6 7 3 15 1 5 Stability
Stability Speed Your turn High Low Dummy, slide, back Stable O(n2)

5 Insertion Sort // a is the name of the array
// nElems stores the number of elements being sorted // This example is for sorting an array of ints int in, out; for(out=1; out<nElems; out++) // out is dividing line { int dummy = a[out]; // dummy Need to modify for sorting different types in = out; // start shifts at out while(in>0 && a[in-1] >= dummy) // until one is smaller, a[in] = a[in-1]; // Slide: shift item right, in--; // go left one position } a[in] = dummy; // Back: insert marked item } // end for

6 Merge Sort Brief Overview

7 How it works Description of MergeSort
MergeSort is a recursive sorting procedure that uses O(n log n) comparisons in the worst case. To sort an array of n elements, we perform the following three steps in sequence: If n<2 then the_array is already sorted. Stop now. Otherwise, n>1, and we perform the following three steps in sequence: Sort the left half of the_array. Sort the right half of the the_array. Merge the now-sorted left and right halves.

8 The smaller value goes first
Mergesort 1. Split the array into two roughly equal “halves.” 2. Sort (recursively) each half using Mergesort. 3. Merge the two sorted halves together. 5 1 3 2 4 7 6 1 3 5 2 4 6 7 Another divide and conquer algorithm. All the work actually happens at the merging phase. 1 3 5 1 2 3 2 4 6 7 The smaller value goes first

9 Overview O(n log (n)) Yes If there is more than one item Speed
Sort the left half of the_array. Sort the right half of the the_array. Merge the now-sorted left and right halves. Speed Stability How it Works Example Low High

10 Mergesort (cont’d) public void mergesort (double[ ] arr,
arr is the name of the array being sorted. from and to are addresses for the range of values being sorted. public void mergesort (double[ ] arr, int from, int to) { if (from <= to) return; int middle = (from + to ) / 2; mergesort (arr, from, middle); mergesort (arr, middle + 1, to); if (arr [middle] > arr [middle + 1]) merge(arr, from, middle, to); } Base case Sort the left values, Sort the right values ‘if’ is an optional shortcut. Both copy and merge are private helper methods. Mergesort needs a temporary array, but it is not a good idea to allocate a large array in a recursive method because it will be allocated at each level of recursion, which may take too much space. Luckily, in this algorithm we can reuse the same temporary array at all levels of recursive calls. For example, we can make temp a private static field in the Mergesort class. Merge the values back together. merge is a separate method.

11 Mergesort (cont’d) Takes roughly n·log2 n comparisons.
Without the shortcut, there is no best or worst case. With the optional shortcut, the best case is when the array is already sorted: takes only (n-1) comparisons. An O(n log n) algorithm. The suggested shortcut is not a canonical “textbook” feature. It’s just an example of how a minor change can dramatically improve a recursive algorithm.

12 Enhanced For Loop For..each loop

13 class MaxAlgorithm { public static void main ( String[] args ) { int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ; int max; // initialize the current maximum max = array[0]; // scan the array for ( int value : array ) { if ( value > max ) // examine the current element max = value ; } System.out.println("The maximum of this array is: " + max ); Java has an enhanced for loop that visits each element of an array in order. It automatically avoids off-by-one bugs. Study the program (above). (There is a colon : separating value and array in the above.)

14 For each assignment, the loop body is executed.
The enhanced for loop for ( int value : array ) { } assigns to value the contents of each cell of the array starting with cell zero and going in order up to the last cell of the array.  For each assignment, the loop body is executed. With this enhanced for loop there is no danger of an index that might go out of bounds, nor any danger of skipping the first or last element. To read this code out loud you say, "For each value in array, ..." Sometimes the enhanced for loop is called a foreach loop.

15 When can you use the For each loop?
Collections Lists ArrayLists Arrays

16 Top Down vs Bottom Up Top Down Bottom Up
The "top down" approach takes a high level definition of the problem and subdivides it into subproblems, which you then do recursively until you're down to pieces that are obvious and easy to code. This is often associated with the "functional decomposition" style of programming, but needn't be. Bottom Up In "bottom up" programming, you identify lower-level tools that you can compose to become a bigger program. Adding new commands that are needed to solve a problem

17 De Morgan’s Law

18 Procedural Abstraction
Breaking down what you want a program to do, but not how to do it.

19 Static vs. Non-Static Methods
Static/ Class methods Do not need to make an object of the class to use it. Like procedures in Pascal Method not tied to an object Math.pow() Math.random() Non-Static Need to make objects of the class in order to use it. Method is tied to the data of the object

20 Concatenate Strings +

21 String Methods

22 Binary Search vs. Sequential Search
Description Big ‘O’ When to use which algorithm

23 Encapsulation Encapsulation is one of the four fundamental OOP concepts.Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface. The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.


Download ppt "Selection Insertion and Merge"

Similar presentations


Ads by Google