SortingBigOh Sorting and "Big Oh" Adapted for ASFA from a presentation by: Barb Ericson Georgia Tech Aug 2007 ASFA AP Computer Science.

Slides:



Advertisements
Similar presentations
Garfield AP Computer Science
Advertisements

CSE Lecture 3 – Algorithms I
Visual C++ Programming: Concepts and Projects
Sorting. “Sorting” When we just say “sorting,” we mean in ascending order (smallest to largest) The algorithms are trivial to modify if we want to sort.
CS203 Programming with Data Structures Sorting California State University, Los Angeles.
Sorting Part 3 CS221 – 3/6/09. Sort Matrix NameWorst Time Complexity Average Time Complexity Best Time Complexity Worst Space (Auxiliary) Selection SortO(n^2)
Simple Sorting Algorithms
Cmpt-225 Sorting. Fundamental problem in computing science  putting a collection of items in order Often used as part of another algorithm  e.g. sort.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Data Structure Algorithm Analysis TA: Abbas Sarraf
Analysis of Algorithm.
Sorting Chapter 6 Chapter 6 –Insertion Sort 6.1 –Quicksort 6.2 Chapter 5 Chapter 5 –Mergesort 5.2 –Stable Sorts Divide & Conquer.
Sorting II/ Slide 1 Lecture 24 May 15, 2011 l merge-sorting l quick-sorting.
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
Simple Sort Algorithms Selection Sort Bubble Sort Insertion Sort.
Analysis of Algorithms Dilemma: you have two (or more) methods to solve problem, how to choose the BEST? One approach: implement each algorithm in C, test.
Simple Sorting Algorithms. 2 Outline We are going to look at three simple sorting techniques: Bubble Sort, Selection Sort, and Insertion Sort We are going.
Abstract Data Types (ADTs) Data Structures The Java Collections API
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Searching – Linear and Binary Searches. Comparing Algorithms Should we use Program 1 or Program 2? Is Program 1 “fast”? “Fast enough”? P1P2.
1 Chapter 24 Developing Efficient Algorithms. 2 Executing Time Suppose two algorithms perform the same task such as search (linear search vs. binary search)
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Chapter 19 Searching, Sorting and Big O
1 Time Analysis Analyzing an algorithm = estimating the resources it requires. Time How long will it take to execute? Impossible to find exact value Depends.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
Chapter 12 Recursion, Complexity, and Searching and Sorting
 2005 Pearson Education, Inc. All rights reserved Searching and Sorting.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
CSC 205 Java Programming II Algorithm Efficiency.
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
SortingBigOh ASFA AP Computer Science A. Big-O refers to the order of an algorithm runtime growth in relation to the number of items I. O(l) - constant.
ECE 103 Engineering Programming Chapter 24 Sorting Herbert G. Mayer, PSU CS Status 6/2/2015 Initial content copied verbatim from ECE 103 material developed.
EFFICIENCY & SORTING II CITS Scope of this lecture Quicksort and mergesort Performance comparison.
Sort Algorithms.
Java Methods Big-O Analysis of Algorithms Object-Oriented Programming
3 – SIMPLE SORTING ALGORITHMS
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Selection Sort Sorts an array by repeatedly finding the smallest.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Review Quick Sort Quick Sort Algorithm Time Complexity Examples
0 Introduction to asymptotic complexity Search algorithms You are responsible for: Weiss, chapter 5, as follows: 5.1 What is algorithmic analysis? 5.2.
 2006 Pearson Education, Inc. All rights reserved. 1 Searching and Sorting.
329 3/30/98 CSE 143 Searching and Sorting [Sections 12.4, ]
1 Algorithms Searching and Sorting Algorithm Efficiency.
CS6045: Advanced Algorithms Sorting Algorithms. Sorting Input: sequence of numbers Output: a sorted sequence.
16 Searching and Sorting.
19 Searching and Sorting.
Sorting and "Big Oh" ASFA AP Computer Science A SortingBigOh.
Sorting Mr. Jacobs.
Searching – Linear and Binary Searches
Algorithmic Efficency
Lecture 14 Searching and Sorting Richard Gesick.
CSC 222: Object-Oriented Programming
Simple Sorting Algorithms
Chapter 20 Searching and Sorting
Lecture 11 Searching and Sorting Richard Gesick.
Searching and Sorting 1-D Arrays
24 Searching and Sorting.
Simple Sorting Algorithms
CSE 373 Data Structures and Algorithms
slides adapted from Marty Stepp
Simple Sorting Algorithms
Workshop for CS-AP Teachers
Simple Sorting Algorithms
Module 8 – Searching & Sorting Algorithms
Presentation transcript:

SortingBigOh Sorting and "Big Oh" Adapted for ASFA from a presentation by: Barb Ericson Georgia Tech Aug 2007 ASFA AP Computer Science A

SortingBigOh Learning Goals Understand several sorting algorithms –Selection Sort, Insertion Sort, Merge Sort, Quicksort Understand how to evaluate the efficiency of an algorithm –Best case, worst case, average case, and a general idea of which is faster –Also "Big Oh"

SortingBigOh Sorting We often want to put data into some order –Ascending or descending Sorting is often shown with array data –But you can sort anything that implements the Comparable Interface Sort Pictures by size –So that the SlideShow class shows the smallest first Sort Sounds by length –So that a PlayList plays the shortest sound first

What is Big-O? Big-O refers to the order of an algorithm runtime growth in relation to the number of items Focus on dominant terms and ignore less significant terms and constants as n grows For example: Selection sort – number of compares is n*(n-1) / 2 n*(n-1) / 2 = n 2 / 2 – n/2 the n 2 / 2 term “dominates” the n /2 term – because as n gets larger n 2 get much larger, faster than n does focus on n 2 / 2 term the constant term is ignored, thus selection sort has order of n-squared: O(n 2 ) SortingBigOh

What is Big-O? Big-O refers to the order of an algorithm runtime growth in relation to the number of items Focus on dominant terms and ignore less significant terms and constants as n grows For example: Merge sort – each call to sort requires 2 recursive sorts and 2 merges of an array of half size the merge operation takes (n/2 – 1) compares O(n) the sorting operation will cause one more level of sorts to be done when the array doubles, two more levels of sorts to be done when the array quadruples, thus sorting is O(m) where n = 2 m  m = log 2 (n)  O(log(n)) combined, the merge sort has O(nlog(n)) SortingBigOh

What is Big-O? Big-O refers to the order of an algorithm runtime growth in relation to the number of items I. O(l) - constant time (Push and pop elements on a stack) II. O(n) - linear time The algorithm requires a number of steps proportional to the size of the task. (Finding the minimum of a list) III. O(n 2 ) - quadratic time The number of operations is proportional to the size of the task squared. (Selection and Insertion sort) IV. O(log n) - logarithmic time (Binary search on a sorted list) V. O(n log n) - "n log n " time (Merge sort and quicksort) SortingBigOh

Selection Sort Algorithm Search the entire array for the smallest element and then swap the smallest with the first element (at index 0) –Continue through the rest of the array doing the same thing (second time with index 1) This uses a nested loop –The outer loop runs from i = 0 to i < a.length – 1 Inner loop runs from j = i+1 to j < a.length

SortingBigOh Selection Sort Code public void selectionSort() { int maxCompare = a.length - 1; int smallestIndex = 0; // loop from 0 to one before last item for (int i = 0; i < maxCompare; i++) { // set smallest index to the one at i smallestIndex = i; // loop from i+1 to end of the array for (int j = i + 1; j < a.length; j++) { if (a[j] < a[smallestIndex]) { smallestIndex = j; } // swap the one at i with the one at smallest index swap(i,smallestIndex); this.printArray("after loop body when i = " + i); } private void swap(int i, int j) { if (i != j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } private void printArray(String message) { System.out.println(message); for (int i : a) System.out.print(i + " "); System.out.println(); }

SortingBigOh How Efficient is Selection Sort? We make n-1 comparisons the first time –Then n-2 comparisons Then n-3 comparisons –And so on till »3, 2, 1 This is a total of –(n-1) + (n-2) + (n-3) + … The equation for the number of steps in an array of n elements is –(n * (n-1)) / 2

SortingBigOh Selection Sort Efficiency It doesn’t matter if the array was sorted or not when we start –Best case == worst case == average case –This algorithm will always take this long! Big O –(n * (n-1)) / 2 is (n 2 -n) / 2 –Keep only the item that grows the fastest as n gets really big so this is O(n 2 )

SortingBigOh Insertion Sort Algorithm Loop through the array and insert the next element in the array into the sorted portion in the correct position –Moving larger values to the right to make room –Start with the second item in the array At index 1 Use a temporary variable to hold the value at the current index

SortingBigOh Insertion Sort Code public void insertionSort() { int temp = 0; int pos = 0; // loop from second element on for (int i = 1; i < a.length; i++) { // save current value at i and set position to i temp = a[i]; pos = i; // shift right any larger elements while (0 < pos && temp < a[pos - 1]) { a[pos] = a[pos - 1]; pos--; } a[pos] = temp; this.printArray("after loop body when i = " + i); }

SortingBigOh Insertion Sort Efficiency Best case –The array is in sorted order when you start Only n-1 comparisons with no swapping Worst case –The array is sorted in decreasing order Need (n * (n – 1)) / 2 comparisons and lots of swapping Average case –On average need (n * (n-1)) / 4 comparisons Big O –(n * (n-1)) / 4 is (n 2 -n) / 4 –Keep only the item that grows the fastest as n gets really big so this is O(n 2 )

SortingBigOh Merge Sort Algorithm If the current array length is 1 return –Base case on the recursion Else –Break the array into two arrays Copy the elements from the original into the new arrays –Create new ArraySorter objects with the new arrays »Do a recursive call to mergeSort on the new ArraySorter objects »Merge the sorted arrays into the original array

SortingBigOh Merge Sort Code public void mergeSort() { // check if there is only 1 element if (a.length == 1) return; // otherwise create two new arrays int[] left = new int[a.length / 2]; for (int i = 0; i < left.length; i++) left[i] = a[i]; int[] right = new int[a.length - left.length]; for (int i = left.length, j=0; i < a.length; i++, j++) right[j] = a[i]; // create new ArraySorter objects ArraySorter sorter1 = new ArraySorter(left); sorter1.printArray("sorter1"); ArraySorter sorter2 = new ArraySorter(right); sorter2.printArray("sorter2"); // do the recursive call sorter1.mergeSort(); sorter2.mergeSort(); // merge the resulting arrays merge(left,right); this.printArray("After merge"); }

SortingBigOh Merge Code /** * Method to merge back into the current array left sorted left array right the sorted right array */ private void merge(int[] left, int[] right) { int leftIndex = 0; // current left index int rightIndex = 0; // current right index int i = 0; // current index in a // merge the left and right arrays into a while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { a[i] = left[leftIndex]; leftIndex++; } else { a[i] = right[rightIndex]; rightIndex++; } i++; } // copy any remaining in left for (int j = leftIndex; j < left.length; j++) { a[i] = left[j]; i++; } // copy any remaining in right for (int j = rightIndex; j < right.length; j++) { a[i] = right[j]; i++; }

SortingBigOh Merge Sort Efficiency Merge sort is usually more efficient than insertion sort and always more efficient than selection sort Best case == Worst Case == Average Case –Merge n elements m times where n = 2 m Big O –About n * m times and m is log 2 (n) so it is n * log(n) –O(n log(n))

SortingBigOh Summary See animations of algorithms at – html/all.html Students need to understand how to sort data –Selection Sort, Insertion Sort, Merge Sort, Quicksort All students should have some idea of the efficiency of each algorithm –should understand best, average, and worst case –need to know "Big Oh"

Merge Sort Timing vs. Selection Sort Figure 2: Merge Sort Timing (blue) versus Selection Sort (red)