1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.

Slides:



Advertisements
Similar presentations
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.
Advertisements

1 A full binary tree A full binary tree is a binary tree in which all the leaves are on the same level and every non leaf node has two children. SHAPE.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
1 Nell Dale Chapter 9 Trees Plus Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -
Sorting A fundamental operation in computer science (many programs need to sort as an intermediate step). Many sorting algorithms have been developed Choose.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 9A Sorting (Concepts)
Visual C++ Programming: Concepts and Projects
Searching and Sorting Algorithms Based on D. S
Sorting Algorithms and Average Case Time Complexity
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
1 Sorting/Searching CS308 Data Structures. 2 Sorting means... l Sorting rearranges the elements into either ascending or descending order within the array.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Sorting Algorithms Selection, Bubble, Insertion and Radix Sort.
Chapter 9 Heaps and Priority Queues. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape must.
C++ Plus Data Structures
Chapter 3: Sorting and Searching Algorithms 3.2 Simple Sort: O(n 2 )
Sorting Algorithms Insertion and Radix Sort. Insertion Sort One by one, each as yet unsorted array element is inserted into its proper place with respect.
Algorithms for Sorting Things. Why do we need to sort things? Internal Telephone Directory –sorted by department then by name My local video store holds.
Searching Arrays Linear search Binary search small arrays
Sorting CS-212 Dick Steflik. Exchange Sorting Method : make n-1 passes across the data, on each pass compare adjacent items, swapping as necessary (n-1.
Algorithm Analysis and Big Oh Notation Courtesy of Prof. Ajay Gupta (with updates by Dr. Leszek T. Lilien) CS 1120 – Fall 2006 Department of Computer Science.
Sorting Text Read Shaffer, Chapter 7 Sorting O(N 2 ) sorting algorithms: – Insertion, Selection, Bubble O(N log N) sorting algorithms – HeapSort, MergeSort,
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
Week 11 Sorting Algorithms. Sorting Sorting Algorithms A sorting algorithm is an algorithm that puts elements of a list in a certain order. We need sorting.
9 Priority Queues, Heaps, and Graphs. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Lecture 5 Searching and Sorting Richard Gesick. The focus Searching - examining the contents of the array to see if an element exists within the array.
1 Data Structures and Algorithms Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus and Robert.
Sorting. Introduction Common problem: sort a list of values, starting from lowest to highest. List of exam scores Words of dictionary in alphabetical.
CSCE 3110 Data Structures & Algorithm Analysis Sorting (I) Reading: Chap.7, Weiss.
Chapter 9 Priority Queues, Heaps, Graphs, and Sets.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
CSE 373 Data Structures and Algorithms
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Sorting CS Sorting means... Sorting rearranges the elements into either ascending or descending order within the array. (we’ll use ascending order.)
1 Nell Dale Chapter 8 Binary Search Trees Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
Sorting and Searching Algorithms CS Sorting means... l The values stored in an array have keys of a type for which the relational operators are.
Chapter 9: Sorting1 Sorting & Searching Ch. # 9. Chapter 9: Sorting2 Chapter Outline  What is sorting and complexity of sorting  Different types of.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
Chapter 9 Heaps and Priority Queues Lecture 18. Full Binary Tree Every non-leaf node has two children Leaves are on the same level Full Binary Tree.
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
Chapter 9: Sorting and Searching Arrays
Alternate Version of STARTING OUT WITH C++ 4th Edition
Lecture 14 Searching and Sorting Richard Gesick.
Chapter 11 Sorting Algorithms and their Efficiency
Design and Analysis of Algorithms
Chapter 9 Priority Queues, Heaps, Graphs, and Sets
Sorting means The values stored in an array have keys of a type for which the relational operators are defined. (We also assume unique keys.) Sorting.
Chapter 10 Sorting and Searching Algorithms
Sorting Algorithms.
Lecture 11 Searching and Sorting Richard Gesick.
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
Straight Selection Sort
C++ Plus Data Structures
Binary Heaps What if we’re mostly concerned with finding the most relevant data? A binary heap is a binary tree (2 or fewer subtrees for each node) A heap.
Chapter 10 Sorting Algorithms
Sorting Algorithms.
Searching/Sorting/Searching
C++ Plus Data Structures
Presentation transcript:

1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva - SUNY Fredonia

2 Sorting means... l The values stored in an array have keys of a type for which the relational operators are defined. (We also assume unique keys.) l Sorting rearranges the elements into either ascending or descending order within the array. (We’ll use ascending order.)

3 Divides the array into two parts: already sorted, and not yet sorted. On each pass, finds the smallest of the unsorted elements, and swaps it into its correct place, thereby increasing the number of sorted elements by one. Straight Selection Sort values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]

4 Selection Sort: Pass One values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] UNSORTEDUNSORTED

5 Selection Sort: End Pass One values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] UNSORTEDUNSORTED SORTED

6 Selection Sort: Pass Two values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] UNSORTEDUNSORTED

7 Selection Sort: End Pass Two values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] UNSORTEDUNSORTED SORTED

8 Selection Sort: Pass Three values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] UNSORTEDUNSORTED SORTED

9 Selection Sort: End Pass Three values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] SORTEDSORTED UNSORTED

10 Selection Sort: Pass Four values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] SORTEDSORTED UNSORTED

11 Selection Sort: End Pass Four values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] SORTEDSORTED

12 Selection Sort: How many comparisons? values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] compares for values[0] 3 compares for values[1] 2 compares for values[2] 1 compare for values[3] =

13 For selection sort in general l The number of comparisons when the array contains N elements is Sum = (N-1) + (N-2)

14 Notice that... Sum = (N-1) + (N-2) Sum = (N-2) + (N-1) 2* Sum = N + N N + N 2 * Sum = N * (N-1) Sum = N * (N-1) 2

15 For selection sort in general l The number of comparisons when the array contains N elements is Sum = (N-1) + (N-2) Sum = N * (N-1) /2 Sum = 0.5 N N Sum = O(N 2 )

template int MinIndex ( ItemType values [ ], int start, int end ) // Post: Function value = index of the smallest value in // values [start].. values [end]. { int indexOfMin = start ; for ( int index = start + 1 ; index <= end ; index++ ) if ( values [ index ] < values [ indexOfMin ] ) indexOfMin = index ; return indexOfMin; } 16

template void SelectionSort ( ItemType values [ ], int numValues ) // Post: Sorts array values[0.. numValues-1 ] into ascending // order by key { int endIndex = numValues - 1 ; for ( int current = 0 ; current < endIndex ; current++ ) Swap ( values [ current ], values [ MinIndex ( values, current, endIndex ) ] ) ; } 17

18 Compares neighboring pairs of array elements, starting with the last array element, and swaps neighbors whenever they are not in correct order. On each pass, this causes the smallest element to “bubble up” to its correct place in the array. Bubble Sort values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]

template void BubbleUp ( ItemType values [ ], int start, int end ) // Post: Neighboring elements that were out of order have been // swapped between values [start] and values [end], // beginning at values [end]. { for ( int index = end ; index > start ; index-- ) if (values [ index ] < values [ index - 1 ] ) Swap ( values [ index ], values [ index - 1 ] ) ; } 19

template void BubbleSort ( ItemType values [ ], int numValues ) // Post: Sorts array values[0.. numValues-1 ] into ascending // order by key { int current = 0 ; while ( current < numValues - 1 ) BubbleUp ( values, current, numValues - 1 ) ; current++ ; } 20

21 One by one, each as yet unsorted array element is inserted into its proper place with respect to the already sorted elements. On each pass, this causes the number of already sorted elements to increase by one. Insertion Sort values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]

22 Works like someone who “inserts” one more card at a time into a hand of cards that are already sorted. To insert 12, we need to make room for it by moving first 36 and then 24. Insertion Sort

Works like someone who “inserts” one more card at a time into a hand of cards that are already sorted. To insert 12, we need to make room for it by moving first 36 and then 24. Insertion Sort 36 12

24 Works like someone who “inserts” one more card at a time into a hand of cards that are already sorted. To insert 12, we need to make room for it by moving first 36 and then 24. Insertion Sort

25 Works like someone who “inserts” one more card at a time into a hand of cards that are already sorted. To insert 12, we need to make room for it by moving first 36 and then 24. Insertion Sort

template void InsertItem ( ItemType values [ ], int start, int end ) // Post: Elements between values [start] and values [end] // have been sorted into ascending order by key. { bool finished = false ; int current = end ; bool moreToSearch = ( current != start ) ; while ( moreToSearch && !finished ) { if (values [ current ] < values [ current - 1 ] ) { Swap ( values [ current ], values [ current - 1 ] ) ; current-- ; moreToSearch = ( current != start ); } else finished = true ; } 26

template void InsertionSort ( ItemType values [ ], int numValues ) // Post: Sorts array values[0.. numValues-1 ] into ascending // order by key { for ( int count = 0 ; count < numValues ; count++ ) InsertItem ( values, 0, count ) ; } 27

Sorting Algorithms and Average Case Number of Comparisons Simple Sorts n Straight Selection Sort n Bubble Sort n Insertion Sort More Complex Sorts n Quick Sort n Merge Sort n Heap Sort O(N 2 ) O(N*log N) 28

29 Heap Sort Approach First, make the unsorted array into a heap by satisfying the order property. Then repeat the steps below until there are no more unsorted elements. l Take the root (maximum) element off the heap by swapping it into its correct place in the array at the end of the unsorted elements. l Reheap the remaining unsorted elements. (This puts the next-largest element into the root position).

30 Swap root element into last place in unsorted array [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root 10 6

31 After swapping root element into its place [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root NO NEED TO CONSIDER AGAIN

32 After reheaping remaining unsorted elements [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root

33 Swap root element into last place in unsorted array [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root

34 After swapping root element into its place [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root NO NEED TO CONSIDER AGAIN 60 5

35 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root After reheaping remaining unsorted elements

36 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root Swap root element into last place in unsorted array

37 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root After swapping root element into its place NO NEED TO CONSIDER AGAIN

38 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root After reheaping remaining unsorted elements

39 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root Swap root element into last place in unsorted array

40 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root After swapping root element into its place NO NEED TO CONSIDER AGAIN

41 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root After reheaping remaining unsorted elements

42 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root Swap root element into last place in unsorted array

43 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root After swapping root element into its place NO NEED TO CONSIDER AGAIN

44 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root After reheaping remaining unsorted elements

45 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root Swap root element into last place in unsorted array

46 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] values root After swapping root element into its place ALL ELEMENTS ARE SORTED

template void HeapSort ( ItemType values [ ], int numValues ) // Post: Sorts array values[ 0.. numValues-1 ] into ascending // order by key { int index ; // Convert array values[ 0.. numValues-1 ] into a heap. for ( index = numValues/2 - 1 ; index >= 0 ; index-- ) ReheapDown ( values, index, numValues - 1 ) ; // Sort the array. for ( index = numValues - 1 ; index >= 1 ; index-- ) { Swap ( values [0], values [index] ); ReheapDown ( values, 0, index - 1 ) ; } 47

48 template void ReheapDown ( ItemType values [ ], int root, int bottom ) // Pre: root is the index of a node that may violate the heap // order property // Post: Heap order property is restored between root and bottom { int maxChild ; int rightChild ; int leftChild ; leftChild = root * ; rightChild = root * ; 48 ReheapDown

if ( leftChild <= bottom )// ReheapDown continued { if ( leftChild == bottom ) maxChild = leftChild; else { if (values [ leftChild ] <= values [ rightChild ] ) maxChild = rightChild ; else maxChild = leftChild ; } if ( values [ root ] < values [ maxChild ] ) { Swap ( values [ root ], values [ maxChild ] ) ; ReheapDown ( maxChild, bottom ) ; } 49

50 Heap Sort: How many comparisons? root In reheap down, an element is compared with its 2 children (and swapped with the larger). But only one element at each level makes this comparison, and a complete binary tree with N nodes has only O(log 2 N) levels

51 Heap Sort of N elements: How many comparisons? (N/2) * O(log N) compares to create original heap (N-1) * O(log N) compares for the sorting loop = O ( N * log N) compares total