COP 3540 Data Structures with OOP

Slides:



Advertisements
Similar presentations
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Advertisements

Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
COP3538 – Data Structures Using OOP Chapter 4 – Stacks and Queues.
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
Sorting I Chapter 8 Kruse and Ryba. Introduction Common problem: sort a list of values, starting from lowest to highest. –List of exam scores –Words of.
ISOM MIS 215 Module 7 – Sorting. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
Data Structures and Algorithms
the fourth iteration of this loop is shown here
Sorting1 Sorting Order in the court!. sorting2 Importance of sorting Sorting a list of values is a fundamental task of computers - this task is one of.
Simple Sorting Algorithms
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 08 / 2010 Instructor: Michael Eckmann.
Algorithm Efficiency and Sorting
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
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.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Chapter 14: Sorting and searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
1 Data Structures and Algorithms Sorting. 2  Sorting is the process of arranging a list of items into a particular order  There must be some value on.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Searching and Sorting Topics Sequential Search on an Unordered File
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
Algorithm Definition An algorithm is a step-by-step solution to a problem.
CSE 373 Data Structures and Algorithms
Data Structures Simple Sorts Phil Tayco Slide version 1.0 Feb. 8, 2015.
CSC 211 Data Structures Lecture 13
Sorting – Insertion and Selection. Sorting Arranging data into ascending or descending order Influences the speed and complexity of algorithms that use.
1 2. Program Construction in Java. 2.9 Sorting 3 The need Soritng into categories is relatively easy (if, else if, switch); here we consider sorting.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
1/47 COP 3540 Data Structures with OOP Simple Sorting Chapter 3.
Comparison-Based Sorting & Analysis Smt Genap
Sorts Tonga Institute of Higher Education. Introduction - 1 Sorting – The act of ordering data Often, we need to order data.  Example: Order a list of.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
By Jonathan Villanueva. Bubble Sorting: the way to sort an array by switching two values that are right next to each other if the first number bigger.
Bubble Sort.
3 – SIMPLE SORTING ALGORITHMS
Sorting & Searching Review. Selection Sort 1. Find the smallest element 2. Move to the front of the array (swap with front) 3. Repeat Steps 1&2, but ignoring.
SORTING Chapter 8 CS Chapter Objectives  To learn how to use the standard sorting methods in the Java API  To learn how to implement the following.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
Chapter 12 Heaps & HeapSort © John Urrutia 2014, All Rights Reserved1.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Data Structures - CSCI 102 Selection Sort Keep the list separated into sorted and unsorted sections Start by finding the minimum & put it at the front.
Recursion Method calls itself iteratively until a base case is met and usually containing the following: if-else for base case with return value increment/decrement.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
1 BUILDING JAVA PROGRAMS CHAPTER 7.2 ARRAY TRAVERSAL ALGORITHMS.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Data Structures Arrays and Lists Part 2 More List Operations.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Assignment 5 is posted. Exercise 8 is very similar to what you will be doing with assignment 5. Exam.
UNIT - IV SORTING By B.Venkateswarlu Dept of CSE.
CS212: Data Structures and Algorithms
Lecture 14 Searching and Sorting Richard Gesick.
Introduction to Search Algorithms
Simple Sorting Algorithms
Design and Analysis of Algorithms
Linear and Binary Search
Describing algorithms in pseudo code
Introduction to Programming
Lecture 11 Searching and Sorting Richard Gesick.
Simple Sorting Methods: Bubble, Selection, Insertion, Shell
Sorting "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The Sorting Hat, Harry Potter.
Simple Sorting Algorithms
Simple Sorting Algorithms
Module 8 – Searching & Sorting Algorithms
Presentation transcript:

COP 3540 Data Structures with OOP 'XYZ' Instructor NotesOOADv4.2 Instructor Notes COP 3540 Data Structures with OOP Chapter 3: Simple Sorting Module 'X' - <name of module>Module 5 - Analysis and Design Overview

'XYZ' Instructor NotesOOADv4.2 Instructor Notes Contents Introduction Simple sorting algorithms Bubble Sort Selection Sort Insertion Sort Sorting Objects Sorting algorithm comparison 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

'XYZ' Instructor NotesOOADv4.2 Instructor Notes Introduction It’s more efficient to work with ordered values “Simple” sorting algorithms Easy to understand Slow (relative to advanced sorting algorithms) Poor performance (> 100 values) O(n2) sorting algorithms Bubble Sort Selection Sort Insertion Sort 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

Basic Process of Simple Sorting Algorithms 'XYZ' Instructor NotesOOADv4.2 Instructor Notes Basic Process of Simple Sorting Algorithms Traverse the array multiple times On each traversal Compare two elements in the array Swap/Copy elements in the array Depends on the algorithm 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

'XYZ' Instructor NotesOOADv4.2 Instructor Notes Bubble Sort Very slow Very simple Process Traverse the array multiple times (until sorted) During each traversal 1. Compare the elements at positions n and n+1 2. If the n element is larger than the n+1 element Swap the two elements 3. Move to the n+1 element 4. Repeat until the last element is reached Start next traversal 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

Bubble Sort Bubble Sort Animation http://cse.iitkgp.ac.in/pds/notes/swf/bubble.swf 1/20/2014 Jim Littleton - COP3538

Bubble Sort Code Listing public class BubbleSort { private int[] array = new int[]{4, 1, 0, 5, 7, 6, 8, 2, 3, 9}; private int numElems = 10; public void bubbleSort() { for(int y = 0; y < numElems; y++) { // Traverse array multiple times for(int x = 0; x < numElems – 1; x++) { // Compare elements in the array if(array[x] > array[x + 1]) { // Compare two elements swap(x, x + 1); } } } public void swap(int pos1, int pos2) { int temp = array[pos1]; array[pos1] = array[pos2]; array[pos2] = temp; 1/20/2014 Jim Littleton - COP3538

Bubble Sort Performance 'XYZ' Instructor NotesOOADv4.2 Instructor Notes Bubble Sort Performance Number of comparisons n2 – n (90 comparisons for 10 elements) Number of swaps 0 to (n2 – n) (0 to 90 swaps for 10 elements) 0, if the array is already sorted (n2 – n) / 2, if the array is randomly sorted (n2 – n), if the array is sorted in reverse order Algorithm can be written more efficiently Don’t compare the sorted section of the array With each traversal, another element is sorted No point in comparing sorted elements Stop sorting early if the array is already sorted If no swaps occur during a traversal of the array The array is already sorted 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

Bubble Sort More Efficient Code Listing public class BubbleSort { private int[] array = new int[]{4, 1, 0, 5, 7, 6, 8, 2, 3, 9}; private int numElems = 10; public void bubbleSort() { boolean swapped = true; // Track whether a swap occurred for(int y = 0; y < numElems && swapped; y++) { // Loop if swapped occurred swapped = false; // Reset swapped status with each traversal for(int x = 0; x < numElems – (y + 1); x++) { // Reduce elements compared if(array[x] > array[x + 1]) { swap(x, x + 1); swapped = true; // Update swapped status is swap occurs } } } public void swap(int pos1, int pos2) { int temp = array[pos1]; array[pos1] = array[pos2]; array[pos2] = temp; 1/20/2014 Jim Littleton - COP3538

Efficient Bubble Sort Performance 'XYZ' Instructor NotesOOADv4.2 Instructor Notes Efficient Bubble Sort Performance Number of comparisons (n2 – n) / 2 (45 comparisons for 10 elements) Number of swaps 0 to (n2 – n) / 2 (0 to 45 swaps for 10 elements) 0, if the array is already sorted (n2 – n) / 4, random order (22.5 swaps/10 elements) (n2 – n) / 2, if the array is sorted in reverse order Bubble Sort has an efficiency of O(n2) Constants like “-1”, “/2” and “/4” are ignored 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

'XYZ' Instructor NotesOOADv4.2 Instructor Notes Bubble Sort – Notes Both compares and swaps are proportional to n2 Sorting is completed in O(n2) time This is slow When an algorithm contains ‟NESTED LOOPS” O(n2) performance should be expected! 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

'XYZ' Instructor NotesOOADv4.2 Instructor Notes Selection Sort Faster than Bubble Sort Simple (nearly as simple as Bubble Sort) Process Traverse the array multiple times During each traversal 1. Initialize pointers Set target (t) and min to first element in the array Set n to the t+1 element in the array 2. Compare the elements at positions n and min 3. If the n element is smaller than the min element Set min to n 4. Move to the n+1 element 5. Repeat until the last element is reached Swap the elements in the min and t positions Start next traversal 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

Selection Sort Selection Sort Animation http://cse.iitkgp.ac.in/pds/notes/swf/selection.swf 1/20/2014 Jim Littleton - COP3538

Selection Sort Code Listing public class SelectionSort { private int[] array = new int[]{4, 1, 0, 5, 7, 6, 8, 2, 3, 9}; private int numElems = 10; public void selectionSort() { int min; for(int y = 0; y < numElems - 1; y++) { // Traverse array multiple times min = y; // Set minimum value pointer for(int x = y + 1; x < numElems; x++) { // Traverses the array if(array[x] < array[min]) { // Compare two elements min = x; // Update minimum value pointer } swap(y, min); // Perform the swap once per traversal } } public void swap(int pos1, int pos2) { int temp = array[pos1]; array[pos1] = array[pos2]; array[pos2] = temp; 1/20/2014 Jim Littleton - COP3538

Selection Sort Performance 'XYZ' Instructor NotesOOADv4.2 Instructor Notes Selection Sort Performance Number of comparisons (n2 – n) / 2 (45 comparisons for 10 elements) Number of swaps n – 1 (9 swaps for 10 elements) Algorithm can be written more efficiently Don’t swap if min value is in the correct position If the min value is already in the correct position No point in swapping the element with itself IMPORTANT!! Unlike the Bubble Sort CANNOT stop sorting if no swap occurs 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

Selection Sort More Efficient Code Listing public class SelectionSort { private int[] array = new int[]{4, 1, 0, 5, 7, 6, 8, 2, 3, 9}; private int numElems = 10; public void selectionSort() { int min; for(int y = 0; y < numElems - 1; y++) { // Traverse array multiple times min = y; // Set minimum value pointer for(int x = y + 1; x < numElems; x++) { // Traverses the array if(array[x] < array[min]) { // Compare two elements min = x; // Update minimum value pointer } if(min > y) { // Only swap the elements if they are not in the same position swap(y, min); // Perform the swap once per traversal } } public void swap(int pos1, int pos2) { int temp = array[pos1]; array[pos1] = array[pos2]; array[pos2] = temp; 1/20/2014 Jim Littleton - COP3538

Efficient Selection Sort Performance 'XYZ' Instructor NotesOOADv4.2 Instructor Notes Efficient Selection Sort Performance Number of comparisons (n2 – n) / 2 (45 comparisons for 10 elements) Number of swaps 0 to (n – 1) (0 to 9 swaps for 10 elements) 0, if the array is already sorted (n – 1) / 2, random order (4.5 swaps/10 elements) (n – 1), if the array is sorted in reverse order Selection Sort has an efficiency of O(n2) Constants like “-1” and “/2” are ignored 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

'XYZ' Instructor NotesOOADv4.2 Instructor Notes Selection Sort – Notes Only compares are proportional to n2 Swaps are proportional to n Sorting is still completed in O(n2) time Comparisons are as slow as the Bubble Sort Swaps are faster than the Bubble Sort Fewer swaps are performed compared to Bubble Sort The Selection Sort is faster than Bubble Sort Especially if swapping two values takes a long time Comparing two values is quick Swapping two values takes time Requires 3 copy (assignment) operations 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

'XYZ' Instructor NotesOOADv4.2 Instructor Notes Insertion Sort Faster than Bubble Sort, as fast as Selection Sort More complicated than the Bubble Sort and Selection Sort Process Traverse the array multiple times During each traversal 1. Initialize pointers Set n to the second element in the array Set temp to the value of the n element 2. Compare the temp value and n-1 element 3. If the temp value is smaller than the n-1 element Move n-1 element to n Set n to n-1 Repeat steps 2 and 3 until temp value is no longer smaller than n-1 element 4. Copy temp value to n-1 element Start next traversal 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

Insertion Sort Insertion Sort Animation http://cse.iitkgp.ac.in/pds/notes/swf/insertion.swf 1/20/2014 Jim Littleton - COP3538

Insertion Sort Code Listing public class InsertionSort { private int[] array = new int[]{4, 1, 0, 5, 7, 6, 8, 2, 3, 9}; private int numElems = 10; public void insertionSort() { int x, temp; for(int y = 1; y < numElems; y++) { // Traverse array multiple times temp = array[y]; // Set minimum value pointer x = y; while(x > 0 && array[x – 1] >= temp) { // Traverses the array array[x] = array[x - 1]; // Move elements x--; } array[x] = temp; // Perform the swap once per traversal } } 1/20/2014 Jim Littleton - COP3538

Insertion Sort Performance 'XYZ' Instructor NotesOOADv4.2 Instructor Notes Insertion Sort Performance Number of comparisons (n2 – n) / 2 (45 comparisons for 10 elements) (n2 – n) / 4 occur for randomly ordered array Number of copies 0 to (n2 – n) / 2 (0 to 45 copies for 10 elements) 0, if all the elements are already in the correct positions (n – 1) / 4, random order (22.5 copies for 10 elements) (n2 – n) / 2, if the array is sorted in reverse order Insertion Sort has an efficiency of O(n2) Constants like “-1”, “/2” and “/4” are ignored 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

'XYZ' Instructor NotesOOADv4.2 Instructor Notes Insertion Sort – Notes Both compares and copies are proportional to n2 Sorting is completed in O(n2) time Copies require less time than swaps (1 swap is equal to 3 copies) Insertion Sort can be twice as fast as Bubble Sort Insertion Sort can be as fast as Selection Sort If the array is sorted in the reverse order (5, 4, 3, 2, 1) Then Insertion Sort is just as slow as Bubble Sort Insertion Sort performs best when the array is nearly sorted Runs at O(n) time rather than O(n2) The Insertion Sort is used by complex algorithms for this very reason See Priority Queue’s Insert algorithm!! (covered in chapter 4) 1/20/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview

Sorting an Array of Objects An array is an array It doesn’t matter what the array contains Primitives values (int, double, etc.) Objects It does matter when sorting an array Primitive values are accessed directly Objects, however, contain a number of properties Every object in an array must be sorted on same property The “key field” is the property the sort is performed on Trying to sort objects directly won’t work The array stores the memory address of each object Will only sort the stored memory addresses 1/20/2014 Jim Littleton - COP3538

Sorting an Array of Objects Sorting an Object Array Example public class Student { private String firstName; // Comparison performed using String.compareTo method private String lastName; // Comparison performed using String.compareTo method private int numCredits; // Regular comparison (numCredits > value) private double gpa; // Regular comparison (gpa > value) private boolean declaredMajor; // Regular comparison (declaredMajor > value) public Student() { } } public class MainClass { private static Student[] student = new Student[10]; public static void main(String[] args) { // Only the comparison statements are listed below if(student[x].firstName.compareTo(student[x + 1].firstName) < 0) if(student[x].firstName.compareToIgnoreCase(student[x + 1].firstName) == 0) if(student[x].numCredits > student[x + 1].numCredits) } 1/20/2014 Jim Littleton - COP3538

'XYZ' Instructor NotesOOADv4.2 Instructor Notes Questions? 1/6/2014 Jim Littleton - COP3538 Module 'X' - <name of module>Module 5 - Analysis and Design Overview