Quadratic Sorting Algorithms

Similar documents
Better Sorting Algorithms

quicksort sorting a vector of pairs the quicksort algorithm C++ code for quicksort partitioning a vector code for partition

the Queue queue ADT using the STL queue designing the simulation simulation with STL queue using STL list as queue using STL vector as queue

Chapter 10 - Notes Applications of Arrays

Simulations. buffer of fixed capacity using the STL deque. modeling arrival times generating and processing jobs

Templates and Vectors

Sol. Sol. a. void remove_items_less_than(int arr[], int size, int value) #include <iostream> #include <ctime> using namespace std;

Elements of C in C++ data types if else statement for loops. random numbers rolling a die

Priority Queues and Huffman Trees

Data Structures Lecture 3 Order Notation and Recursion

Lists. linking nodes. constructors. chasing pointers. MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010.

Due Date: See Blackboard

Hashing. mapping data to tables hashing integers and strings. aclasshash_table inserting and locating strings. inserting and locating strings

CS302 Midterm Exam Answers & Grading James S. Plank September 30, 2010

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

the Stack stack ADT using the STL stack are parentheses balanced? algorithm uses a stack adapting the STL vector class adapting the STL list class

Due Date: See Blackboard

Review of the Lectures 21-26, 30-32

Graphs. directed and undirected graphs weighted graphs adjacency matrices. abstract data type adjacency list adjacency matrix

Binary Search. the towers of Hanoi recursive C++ code. sorted vectors of numbers fast power function. when not to use recursion memoization

Iterators. node UML diagram implementing a double linked list the need for a deep copy. nested classes for iterator function objects

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

Lectures 19, 20, 21. two valid iterators in [first, last) such that i precedes j, then *j is not less than *i.

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements

Hashing. inserting and locating strings. MCS 360 Lecture 28 Introduction to Data Structures Jan Verschelde, 27 October 2010.

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation

Week 3: Pointers (Part 2)

Overview of Sorting Algorithms

Queue Implementations

SCJ2013 Data Structure & Algorithms. Bubble Sort. Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi

Sorting vectors. Sorting. Sorting. Sorting. Another common task: sort v[a..b] Let T be a type with a operation, which is a total order.

Local and Global Variables

selectors, methodsinsert() andto_string() the depth of a tree and a membership function

Ch 8. Searching and Sorting Arrays Part 1. Definitions of Search and Sort

Lecture 23: Pointer Arithmetic

Linked List using a Sentinel

Review Questions for Final Exam

Sorting. Quicksort analysis Bubble sort. November 20, 2017 Hassan Khosravi / Geoffrey Tien 1

Object oriented programming

Recursion. Example R1

Topics. bool and string types input/output library functions comments memory allocation templates classes

SAMPLE OF THE STUDY MATERIAL PART OF CHAPTER 6. Sorting Algorithms

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

Sorting. Bringing Order to the World

Lecture Notes 14 More sorting CSS Data Structures and Object-Oriented Programming Professor Clark F. Olson

Linear Search. Sorting Algorithms. linear search code. Sorting in Ascending Order Selection Sort. Selection sort algorithm

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

BITG 1113: Array (Part 1) LECTURE 8

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

Arrays. Week 4. Assylbek Jumagaliyev

The University Of Michigan. EECS402 Lecture 07. Andrew M. Morgan. Sorting Arrays. Element Order Of Arrays

Chapter Four: Loops II

Lab Instructor : Jean Lai

Quad Doubles on a GPU

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

CSE030 Fall 2012 Final Exam Friday, December 14, PM

1 Unit 8 'for' Loops

Lab 7 (50 pts) Due Sunday, May 20)

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Computer Science II Lecture 2 Strings, Vectors and Recursion

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

Sorting. Weiss chapter , 8.6

Programming Fundamentals

Unit 7. 'while' Loops

Intermediate Programming, Spring 2017*

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

Review Problems for Final Exam. 1. What is the output of the following program? #include <iostream> #include <string> using namespace std;

PIC 10A. Final Review

1 a = [ 5, 1, 6, 2, 4, 3 ] 4 f o r j i n r a n g e ( i + 1, l e n ( a ) 1) : 3 min = i

Summary of basic C++-commands

Review of Important Topics in CS1600. Functions Arrays C-strings

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

Problem Solving: Storyboards for User Interaction

Elementary Sorting Algorithms

C++ Programming: From Problem Analysis to Program Design, Third Edition

ENGI 1020 Introduction to Computer Programming J U L Y 5, R E Z A S H A H I D I

Computer Programming

Module Contact: Dr Pierre Chardaire, CMP Copyright of the University of East Anglia Version 1

CSCI 102L - Data Structures Midterm Exam #2 Spring 2011

CS103L SPRING 2017 UNIT 8: RECURSION

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Why Is Repetition Needed?

1. (18 pts) Short Answer. Provide brief (1-3 sentence) answers to the following:

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold

Sorting Algorithms. + Analysis of the Sorting Algorithms

Programming Language. Functions. Eng. Anis Nazer First Semester

Administrivia. HW on recursive lists due on Wednesday. Reading for Wednesday: Chapter 9 thru Quicksort (pp )

Transcription:

Quadratic Sorting Algorithms 1 Using C++ Sorting sorting a vector of pairs setting up C++ code 2 Selection Sort the selection sort algorithm C++ code for selection sort 3 Bubble Sort the bubble sort algorithm C++ code for bubble sort 4 Insertion Sort the insertion sort algorithm C++ code for insertion sort MCS 360 Lecture 30 Introduction to Data Structures Jan Verschelde, 6 November 2017 Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 1 / 29

Quadratic Sorting Algorithms 1 Using C++ Sorting sorting a vector of pairs setting up C++ code 2 Selection Sort the selection sort algorithm C++ code for selection sort 3 Bubble Sort the bubble sort algorithm C++ code for bubble sort 4 Insertion Sort the insertion sort algorithm C++ code for insertion sort Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 2 / 29

sorting a vector of pairs Consider vector< pair<int,char> > v as a frequency table. We sort on the int key. 5 random items : (82,i)(90,d)(42,x)(54,r)(31,z) We sort in increasing order of keys: 1 customized compare function, 2 illustrate stable sort. Equal keys retain their relative order in a stable sort. For example: (23,c).. (23,a) (23,c) (23,a) We assume we sort container with random-access iterator. For convenience: use subscripting operator []on vectors. Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 3 / 29

Motivation why bother with quadratic sorts? After STL sort and stable sort, we study selection, bubble, and insertion sort. The algorithms are quadratic cost sorting algorithms, i.e.: for sequences of size n, their cost is O(n 2 ). Why bother with these less efficient algorithms? 1 these algorithms are straightforward 2 for moderate dimensions, quadratic cost is not so bad 3 understand the basis for advanced sorting algorithms Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 4 / 29

Quadratic Sorting Algorithms 1 Using C++ Sorting sorting a vector of pairs setting up C++ code 2 Selection Sort the selection sort algorithm C++ code for selection sort 3 Bubble Sort the bubble sort algorithm C++ code for bubble sort 4 Insertion Sort the insertion sort algorithm C++ code for insertion sort Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 5 / 29

the include directives #include <iostream> #include <cstdlib> #include <ctime> #include <vector> #include <algorithm> using namespace std; Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 6 / 29

a random vector vector< pair<int,char> > random_vector ( int n ) vector< pair<int,char> > v; for(int i=0; i<n; i++) pair<int,char> p; p.first = 10 + (rand() % 90); p.second = a + rand() % 26; v.push_back(p); } } return v; Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 7 / 29

write and comparison void write_vector ( vector< pair<int,char> > v ) for(int i=0; i<v.size(); i++) cout << "(" << v[i].first << "," << v[i].second << ")"; } struct less_than // defines "<" bool operator()(const pair<int,char>& a, const pair<int,char>& b) return (a.first < b.first); } }; Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 8 / 29

themainprogram int main() cout << "give n : "; int n; cin >> n; srand(time(0)); vector< pair<int,char> > v = random_vector(n); cout << n << " random items : "; write_vector(v); cout << endl; cout << "stable sort? (y/n) "; char ans; cin >> ans; if(ans == y ) stable_sort(v.begin(),v.end(),less_than()); else sort(v.begin(),v.end(),less_than()); cout << "the sorted vector : "; write_vector(v); cout << endl; Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 9 / 29

Quadratic Sorting Algorithms 1 Using C++ Sorting sorting a vector of pairs setting up C++ code 2 Selection Sort the selection sort algorithm C++ code for selection sort 3 Bubble Sort the bubble sort algorithm C++ code for bubble sort 4 Insertion Sort the insertion sort algorithm C++ code for insertion sort Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 10 / 29

Selection Sort Sort a sequence of n elements: 1 get the minimum of the sequence, 2 place the minimum in front of the sequence, 3 sort the remaining n 1 elements. With an index i we keep track of the elements in the sequence still to be sorted. For i from 0 to n 1: 1 select the minimum m in v i, v i+1,...,v n ; 2 if m v i then swap m v i. Loop invariant: first i elements are smallest. Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 11 / 29

running an example 5 random items : (24,b)(96,k)(12,t)(99,g)(26,w) after 2 <-> 0 : (12,b)(96,k)(24,t)(99,g)(26,w) after 2 <-> 1 : (12,b)(24,k)(96,t)(99,g)(26,w) after 4 <-> 2 : (12,b)(24,k)(26,t)(99,g)(96,w) after 4 <-> 3 : (12,b)(24,k)(26,t)(96,g)(99,w) the sorted vector : (12,b)(24,k)(26,t)(96,g)(99,w) Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 12 / 29

Quadratic Sorting Algorithms 1 Using C++ Sorting sorting a vector of pairs setting up C++ code 2 Selection Sort the selection sort algorithm C++ code for selection sort 3 Bubble Sort the bubble sort algorithm C++ code for bubble sort 4 Insertion Sort the insertion sort algorithm C++ code for insertion sort Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 13 / 29

code for selection sort void sort ( vector< pair<int,char> >& v ) for(int i=0; i<v.size()-1; i++) int m = v[i].first; int k = i; for(int j=i+1; j<v.size(); j++) if(v[j].first < m) m = v[j].first; k = j; } if(k!= i) v[k].first = v[i].first; v[i].first = m; } } } Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 14 / 29

Cost Analysis The cost of a sort depends on 1 the number of comparisons, 2 the number of assignments. Looking at relevant parts of code: for(int i=0; i<v.size()-1; i++) for(int j=i+1; j<v.size(); j++) if(v[j].first < m) Let n = v.size(), then n i 1 comparisons are performed for i from 0 to n 1. #comparisons: n 1 + n 2 + + 2 + 1 = 1 2n(n 1) Worst case for swaps? v is given in reverse order. Best case? v is already sorted. Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 15 / 29

Quadratic Sorting Algorithms 1 Using C++ Sorting sorting a vector of pairs setting up C++ code 2 Selection Sort the selection sort algorithm C++ code for selection sort 3 Bubble Sort the bubble sort algorithm C++ code for bubble sort 4 Insertion Sort the insertion sort algorithm C++ code for insertion sort Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 16 / 29

Bubble Sort How verify that a vector is already sorted? We run through the sequence: as long as two consecutive elements are out of order: swap. Largest element get swapped to the end. For i from 0 to n 1do 1 assume sequence is sorted; 2 for j from 0 to n i 1do if vj > v j+1 then swap v j v j+1 and sequence was not sorted; 3 if no swap occurred, then leave the loop. Loop invariant: last i elements are largest. Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 17 / 29

running an example 5 random items : (62,r)(52,y)(30,k)(70,l)(31,e) after 0 <-> 1 : (52,y)(62,r)(30,k)(70,l)(31,e) after 1 <-> 2 : (52,y)(30,k)(62,r)(70,l)(31,e) after 3 <-> 4 : (52,y)(30,k)(62,r)(31,e)(70,l) after 0 <-> 1 : (30,k)(52,y)(62,r)(31,e)(70,l) after 2 <-> 3 : (30,k)(52,y)(31,e)(62,r)(70,l) after 1 <-> 2 : (30,k)(31,e)(52,y)(62,r)(70,l) the sorted vector : (30,k)(31,e)(52,y)(62,r)(70,l) Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 18 / 29

Quadratic Sorting Algorithms 1 Using C++ Sorting sorting a vector of pairs setting up C++ code 2 Selection Sort the selection sort algorithm C++ code for selection sort 3 Bubble Sort the bubble sort algorithm C++ code for bubble sort 4 Insertion Sort the insertion sort algorithm C++ code for insertion sort Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 19 / 29

code for bubble sort void sort ( vector< pair<int,char> >& v ) for(int i=0; i<v.size()-1; i++) bool sorted = true; for(int j=0; j<v.size()-i-1; j++) if(v[j].first > v[j+1].first) pair<int,char> tmp = v[j]; v[j] = v[j+1]; v[j+1] = tmp; } sorted = false; } } if(sorted) break; Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 20 / 29

Cost Analysis Again we count comparisons and assignments. Look at relevant parts of the code: for(int i=0; i<v.size()-1; i++) for(int j=0; j<v.size()-i-1; j++) if(v[j].first > v[j+1].first) Let n = v.size(), then n i 1 comparisons are performed for i from 0 to n 1. #comparisons: n 1 + n 2 + + 2 + 1 = 1 2n(n 1) Bubble sort seems just as good (or bad) as selection sort, but it swaps adjacent elements and works on linked lists. Best case? Given vector is already sorted. Worst case for swaps? v is in reverse order. Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 21 / 29

Quadratic Sorting Algorithms 1 Using C++ Sorting sorting a vector of pairs setting up C++ code 2 Selection Sort the selection sort algorithm C++ code for selection sort 3 Bubble Sort the bubble sort algorithm C++ code for bubble sort 4 Insertion Sort the insertion sort algorithm C++ code for insertion sort Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 22 / 29

Insertion Sort Imagine sorting playing cards: 1 hold in left hand cards already picked up, 2 insert newly picked card in left hand. Denote by index i the start of the sequence of n elements still to be inserted. For i from 0 to n 1do 1 find j < i: v j v i (if j = i 1, then sorted); 2 if j i 1: shift v j+1...v i 1 one spot to the right and insert v i at the j-th spot. Loop invariant: first i elements are sorted. Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 23 / 29

running an example 5 random items : (87,i)(48,v)(36,h)(73,a)(63,h) after 1 <-> 0 : (48,v)(87,i)(36,h)(73,a)(63,h) after 2 <-> 0 : (36,h)(48,v)(87,i)(73,a)(63,h) after 3 <-> 2 : (36,h)(48,v)(73,a)(87,i)(63,h) after 4 <-> 2 : (36,h)(48,v)(63,h)(73,a)(87,i) the sorted vector : (36,h)(48,v)(63,h)(73,a)(87,i) Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 24 / 29

Quadratic Sorting Algorithms 1 Using C++ Sorting sorting a vector of pairs setting up C++ code 2 Selection Sort the selection sort algorithm C++ code for selection sort 3 Bubble Sort the bubble sort algorithm C++ code for bubble sort 4 Insertion Sort the insertion sort algorithm C++ code for insertion sort Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 25 / 29

code for insertion sort void sort ( vector< pair<int,char> >& v ) for(int i=1; i<v.size(); i++) int j=i-1; while((j >= 0) && (v[i].first < v[j].first)) j--; if(++j < i) pair<int,char> tmp = v[i]; for(int k=i-1; k>=j; k--) v[k+1] = v[k]; v[j] = tmp; } } } Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 26 / 29

Cost Analysis Once more we count comparisons and assignments. We look at relevant part of the code: for(int i=1; i<v.size(); i++) int j=i-1; while((j >= 0) && (v[i].first < v[j].first)) j--; Denote n = v.size(), we insert n 1 elements and in the worst case we make n 1 + n 2 + + 2 + 1 = 1 2n(n 1) comparisons. In the best case, when sorted: n 1 comparisons. Cost of shifting elements is smaller with linked list. Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 27 / 29

comparison of quadratic sorts #comparisons #exchanges sort cases best worst best worst selection O(n 2 ) O(n 2 ) O(1) O(n) bubble O(n) O(n 2 ) O(1) O(n 2 ) insertion O(n) O(n 2 ) O(n) O(n 2 ) Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 28 / 29

Summary + Exercises Started chapter 10 on sorting algorithms with quadratic cost: selection, bubble, and insertion sort. Exercises: 1 Write a recursive function for selection sort. 2 Give code for a bubble sort on a linked list. 3 Change the code for insertion sort to take on input random-access iterators to begin and end of a vector. 4 Modify the sort functions to count the #comparisons and #swaps. Run 10 tests on random vectors of length 100 with selection, bubble, and insertion sorts. Record the #comparisons and #swaps inatable. Introduction to Data Structures (MCS 360) Quadratic Sorting Algorithms L-30 6 November 2017 29 / 29