Selection Insertion and Merge

Slides:



Advertisements
Similar presentations
Back to Sorting – More efficient sorting algorithms.
Advertisements

The Merge Sort Textbook Authors: Ken Lambert & Doug Nance PowerPoint Lecture by Dave Clausen.
Garfield AP Computer Science
HST 952 Computing for Biomedical Scientists Lecture 9.
Efficient Sorts. Divide and Conquer Divide and Conquer : chop a problem into smaller problems, solve those – Ex: binary search.
Ver. 1.0 Session 5 Data Structures and Algorithms Objectives In this session, you will learn to: Sort data by using quick sort Sort data by using merge.
Insertion sort, Merge sort COMP171 Fall Sorting I / Slide 2 Insertion sort 1) Initially p = 1 2) Let the first p elements be sorted. 3) Insert the.
By D.Kumaragurubaran Adishesh Pant
1 Divide and Conquer Binary Search Mergesort Recurrence Relations CSE Lecture 4 – Algorithms II.
(c) , University of Washington
Recursion, Complexity, and Searching and Sorting By Andrew Zeng.
Chapter 16: Searching, Sorting, and the vector Type.
1 Programming with Recursion. 2 Recursive Function Call A recursive call is a function call in which the called function is the same as the one making.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1 post-mortem  Recursive running time.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
Sorting and Searching Pepper. Common Collection and Array Actions Sort in a certain order ◦ Max ◦ Min Shuffle Search ◦ Sequential (contains) ◦ Binary.
Searching and Sorting Recursion, Merge-sort, Divide & Conquer, Bucket sort, Radix sort Lecture 5.
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Searching and Sorting 14ACEHRPT Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented.
Java Methods 11/10/2015. Learning Objectives  Be able to read a program that uses methods.  Be able to write a write a program that uses methods.
CSE 250 – Data Structures. Today’s Goals  First review the easy, simple sorting algorithms  Compare while inserting value into place in the vector 
Chapter 16: Searching, Sorting, and the vector Type.
Array Review Selection Sort Get out your notes.. Learning Objectives Be able to dry run programs that use arrays Be able to dry run programs that use.
Searching and Sorting Searching algorithms with simple arrays
Prof. U V THETE Dept. of Computer Science YMA
Lecture 25: Searching and Sorting
Using recursion for Searching and Sorting
Sorts, CompareTo Method and Strings
Fundamentals of Algorithms MCS - 2 Lecture # 11
Chapter 16: Searching, Sorting, and the vector Type
16 Searching and Sorting.
Sorting Mr. Jacobs.
Week 13: Searching and Sorting
Comparing Objects in Java
COP 3503 FALL 2012 Shayan Javed Lecture 15
Lecture 14 Searching and Sorting Richard Gesick.
Java Programming: Guided Learning with Early Objects
Recitation 13 Searching and Sorting.
COMP 53 – Week Seven Big O Sorting.
About the Presentations
Fast Sorting "The bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems."
Teach A level Computing: Algorithms and Data Structures
Array Review Selection Sort
Chapter 4: Divide and Conquer
Sorting Algorithms IT12112 Lecture 07.
Advanced Sorting Methods: Shellsort
Building Java Programs
SORTING AND SEARCHING.
Hassan Khosravi / Geoffrey Tien
Sorts on the AP Exam Insertion Sort.
Lecture 11 Searching and Sorting Richard Gesick.
25 Searching and Sorting Many slides modified by Prof. L. Lilien (even many without an explicit message indicating an update). Slides added or modified.
Search,Sort,Recursion.
24 Searching and Sorting.
Sub-Quadratic Sorting Algorithms
Topic 17 Faster Sorting "The bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical.
Sorting Chapter 8.
Dry Run Practice Use Methods with an Insertion Sort
CSE 373 Data Structures and Algorithms
CSC 143 Java Sorting.
Amortized Analysis and Heaps Intro
Sorting and Asymptotic Complexity
Array Review Selection Sort
Advanced Sorting Methods: Shellsort
Presentation transcript:

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

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

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)

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

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

Merge Sort Brief Overview

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.

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

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 30 15 20 10 8 14 7 21

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.

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.

Enhanced For Loop For..each loop

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.)

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.

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

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

De Morgan’s Law

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

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

Concatenate Strings +

String Methods

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

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.