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

Similar documents
Chapter 10 - Notes Applications of Arrays

C/C++ Programming Lecture 18 Name:

LECTURE 17. Array Searching and Sorting

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

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

CmpSci 187: Programming with Data Structures Spring 2015

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

CS 115 Exam 3, Fall 2009

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

Sorting and Searching Algorithms

Solutions to Chapter 8

SORTING AND SEARCHING

Arrays. Week 4. Assylbek Jumagaliyev

! Search: find an item in an array, return the. ! Sort: rearrange the items in an array into some. ! There are various methods (algorithms) for

The University Of Michigan. EECS402 Lecture 05. Andrew M. Morgan. Savitch Ch. 5 Arrays Multi-Dimensional Arrays. Consider This Program

Chapter 10 Sorting and Searching Algorithms

Data Structures and Algorithms for Engineers

C++ PROGRAMMING SKILLS Part 4: Arrays

CS 106 Introduction to Computer Science I

Algorithm Analysis. Performance Factors

Module 08: Searching and Sorting Algorithms

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return

Chapter Objectives. List Processing. Chapter 10: Applications of Arrays and Strings. Java Programming: Program Design Including Data Structures

Data Types. Operators, Assignment, Output and Return Statements

Sorting. Task Description. Selection Sort. Should we worry about speed?

Arrays and Applications

CS 12 Fall 2003 Solutions for mid-term exam #2

Topics. Sorting. Sorting. 1) How can we sort data in an array? a) Selection Sort b) Insertion Sort

Sorting Algorithms. Array Data is being arranged in ascending order using the bubble sort algorithm. #1 #2 #3 #4 #5 #6 #7

EECS402 Lecture 02. Functions. Function Prototype

Searching Elements in an Array: Linear and Binary Search. Spring Semester 2007 Programming and Data Structure 1

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

Bubble sort starts with very first two elements, comparing them to check which one is greater.

Introduction to Computer Science Midterm 3 Fall, Points

8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

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

Walls & Mirrors Chapter 9. Algorithm Efficiency and Sorting

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

8.1. Chapter 8: Introduction to Search Algorithms. Linear Search. Linear Search. Linear Search - Example 8/23/2014. Introduction to Search Algorithms

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

Ch 5-2. Arrays Part 2

Lecture 6 Sorting and Searching

Topics Applications Most Common Methods Serial Search Binary Search Search by Hashing (next lecture) Run-Time Analysis Average-time analysis Time anal

Recursive Algorithms. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

CS150 Intro to CS I. Fall Fall 2017 CS150 - Intro to CS I 1

LECTURE 08 SEARCHING AND SORTING ARRAYS

Fundamental problem in computing science. putting a collection of items in order. Often used as part of another algorithm

There are two possible results from a search: either you find the item you are looking for, or you don't.

for (int outercounter = nums.length - 1; outercounter > 0 && swappedthatturn; outercounter --

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

Sorting/Searching and File I/O. Sorting Searching Reading for this lecture: L&L

Sorting. Sorting. Stable Sorting. In-place Sort. Bubble Sort. Bubble Sort. Selection (Tournament) Heapsort (Smoothsort) Mergesort Quicksort Bogosort

12/1/2016. Sorting. Savitch Chapter 7.4. Why sort. Easier to search (binary search) Sorting used as a step in many algorithms

CSE 2123 Sorting. Jeremy Morris

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

Data Structures Lecture 3 Order Notation and Recursion

Week 3: Pointers (Part 2)

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)

Learning Recursion. Recursion [ Why is it important?] ~7 easy marks in Exam Paper. Step 1. Understand Code. Step 2. Understand Execution

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

Searching and Sorting

Sorting is ordering a list of objects. Here are some sorting algorithms

To become familiar with array manipulation, searching, and sorting.

Component 02. Algorithms and programming. Sorting Algorithms and Searching Algorithms. Matthew Robinson

CS 315 Data Structures mid-term 2

Fun facts about recursion

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

Sorting and Searching

10/21/ Linear Search The linearsearch Algorithm Binary Search The binarysearch Algorithm

106B Final Review Session. Slides by Sierra Kaplan-Nelson and Kensen Shi Livestream managed by Jeffrey Barratt

Final Exam Solutions PIC 10B, Spring 2016

Searching and Sorting

Sorting: Overview/Questions

Introduction to Computers and Programming

Computer Science & Engineering 150A Problem Solving Using Computers

Introduction to Computers and Programming. Today

Searching & Sorting in Java Bubble Sort

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Sorting Algorithms. Biostatistics 615 Lecture 7

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

QuickSort. CIS 15 : Spring 2007

CS 310 Advanced Data Structures and Algorithms

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

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Priority queues. Priority queues. Priority queue operations

CHAPTER 7 Iris Hui-Ru Jiang Fall 2008

Search Lesson Outline

Today. CISC101 Reminders & Notes. Searching in Python - Cont. Searching in Python. From last time

Algorithms. Chapter 8. Objectives After studying this chapter, students should be able to:

What is an algorithm?

DATA STRUCTURES AND ALGORITHMS. Sorting algorithms (insertion sort, bubble sort, selection sort)

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Lecture 19 Sorting Goodrich, Tamassia

CSCI 136 Data Structures & Advanced Programming. Lecture 12 Fall 2018 Profs Bill & Jon

Sorting and Searching. Sudeshna Sarkar 7 th Feb 2017

1. Write step by step code to delete element from existing Doubly Linked List. Suppose that all declarations are done

Transcription:

The University Of Michigan Lecture 07 Andrew M. Morgan Sorting Arrays Element Order Of Arrays Arrays are called "random-access" data structures This is because any element can be accessed at any time Other data structures (called "linked structures", that will be discussed later in the course, do not have this property Array elements remain in the order that the programmer puts them A very common operation is to sort the elements in an array Much research has been done on sorting, and entire books are written on the subject Main advantage of sorted arrays over unsorted arrays Efficiency of finding an element in the array Andrew M Morgan 2 1

Useful Array Functions #1 Write a function to print array contents to screen, one element per line, preceded with the index number void printarray( int iary[] cout << "Printing Array Contents" << endl; for (i = 0; i < numaryelems; i++ cout << "i: " << iary[i] << endl; Andrew M Morgan 3 Useful Array Functions #2 Write a function to fill an array of integers with random values in a given range void fillrandomarray( int min, int max, int iary[] for (i = 0; i < numaryelems; i++ //Assign current element to a random value iary[i] = rand( % (max - min + 1 + min; Andrew M Morgan 4 2

Useful Array Functions #3 Write a function to find the array index that contains the minimum value in a given range of elements of an array int findindexofmininrange( int startindex, int endindex, const int iary[] int minindex; int minval; //Start by assuming that the //first one is the min minval = iary[startindex]; minindex = startindex; //Continued, next column //Loop over others looking //for smaller values than min for (i = startindex + 1; i <= endindex; i++ if (iary[i] < minval minval = iary[i]; minindex = i; return (minindex; Andrew M Morgan 5 Support Function - Swap Write a function that swaps the contents of two integer variables Function must take two parameters by reference in order to change two values from the calling function void swapints( int &i1, int &i2 int temp; //Save the first value, since it will be //overwritten with the second value temp = i1; i1 = i2; i2 = temp; Andrew M Morgan 6 3

Selection Sort Selection Sort: One of the easiest and most common sorting algorithms Search through remaining portion of array looking for minimum value Swap the minimum value with the lowest numbered element previously unplaced Initial Unsorted Array 2 4 7 16 2 81 7 16 Array element to be swapped with minimum Array element containing minimum value 2 81 7 16 Selection Sort Algorithm 2 16 7 81 2 16 7 81 2 16 7 81 2 16 7 81 Andrew M Morgan 7 Final Sorted Array 2 16 6 81 7 102 Selection Sort Implementation Write a function to implement the selection sort algorithm on an array of integer values void selectionsort( int iary[] int minind; for (i = 0; i < numaryelems - 1; i++ //find index of min value between i and end of array minind = findindexofmininrange(i, numaryelems - 1, iary; if (minind!= i swapints(iary[i], iary[minind]; Andrew M Morgan 8 4

Selection Sort Demo Write a program to demonstrate the selection sort implementation int main( const int NUM_ELEMS = 10; int arytosort[num_elems]; //Fill up the array and print it out... fillrandomarray(30, 100, NUM_ELEMS, arytosort; printarray(num_elems, arytosort; //Now sort the array selectionsort(num_elems, arytosort; //print out the final sorted array printarray(num_elems, arytosort; return (0; Andrew M Morgan 9 Selection Sort Demo, Output Printing Array Contents i: 63 i: 93 i: 57 i: 38 i: 79 i: 32 i: 100 i: 86 Printing Array Contents i: 32 i: 38 i: 57 i: 63 i: 79 i: 86 i: 93 i: 100 Original contents of randomly fill array Sorted array results of selection sort demo Andrew M Morgan 10 5

Intro To Bubble Sort Bubble sort is similar to selection sort Finding the minimum value is not required More intermediate swaps are performed initially, less later Main idea: Loop backwards over array through unsorted portion of array If the element before the current element is less, swap elements Array elements that have been sorted Algorithm Iteration Initial Array 2 4 2 4 X 2 4 X 2 4 1 4 2 13 1 81 1 81 2 13 2 13 X X 1 81 2 13 X 1 81 2 13 2 81 2 81 X X 2 19 3 81 2 19 2 19 3 81 3 81 X 2 19 3 55 4 81 2 19 3 55 5 81 Andrew M Morgan 11 Final Sorted Array Bubble Sort Implementation Write a function to implement the bubble sort algorithm void bubblesort( int iary[] int iter; for (iter = 0; iter < numaryelems; iter++ //loop backwards from end through unsorted part of array for (i = numaryelems - 1; i > iter; i-- //"bubble up" the element if it is lower than previous one if (iary[i] < iary[i - 1] swapints(iary[i], iary[i-1]; Andrew M Morgan 12 6

Bubble Sort Demo Write a program to demonstrate the bubble sort implementation int main( const int NUM_ELEMS = 10; int arytosort[num_elems]; //Fill up the array and print it out... fillrandomarray(30, 100, NUM_ELEMS, arytosort; printarray(num_elems, arytosort; //Now sort the array bubblesort(num_elems, arytosort; //print out the final sorted array printarray(num_elems, arytosort; return (0; Andrew M Morgan 13 Bubble Sort Demo, Output Printing Array Contents i: 63 i: 93 i: 57 i: 38 i: 79 i: 32 i: 100 i: 86 Printing Array Contents i: 32 i: 38 i: 57 i: 63 i: 79 i: 86 i: 93 i: 100 Original contents of randomly fill array Sorted array results of bubble sort demo Andrew M Morgan 14 7

Analysis When Array Elements Are Random The following compares the two sort algorithms discussed The arrays were filled with initial values that are completely random Selection Sort Analysis Output Total Time : 3 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 24631 Total Time : 11 Num Swaps: 49259 Bubble Sort Analysis Output Total Time : 10 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 152901558 Total Time : 37 Num Swaps: 615973663 Andrew M Morgan 15 Analysis When Mostly Sorted Initially What about cases then the array is mostly in a sorted order to begin with? This analysis was done on an array that was "mostly" sorted Selection Sort Analysis Output Total Time : 3 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 17686 Bubble Sort Analysis Output Total Time : 3 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 212008 Total Time : 12 Num Swaps: 40964 Total Time : 14 Num Swaps: 187285 Total Time : 45 Num Ary Elems: 100000 Num Compares: 704982704 Num Swaps: 79172 Total Time : 57 Num Ary Elems: 100000 Num Compares: 704982704 Num Swaps: 260975 Andrew M Morgan 16 8

Analysis When Sorted Array Has New Elems The following analysis was done when a large array is sorted, except for 5 elements at the end of the array Modified Bubble Sort: Stops algorithm if array ends up being fully sorted along the way Selection Sort Analysis Total Time : 11 Num Swaps: 48466 Bubble Sort Analysis Total Time : 15 Num Swaps: 188806 Modified Bubble Sort Analysis Total Time : 0 Num Compares: 299979 Num Swaps: 188806 Andrew M Morgan 17 Implementation Of Modified Bubble Sort void newbubblesort( int iary[] int iter; bool swapnec; for (iter = 0; iter < numaryelems; iter++ swapnec = false; for (i = numaryelems - 1; i > iter; i-- if (iary[i] < iary[i - 1] swapnec = true; swapints(iary[i], iary[i-1]; if (!swapnec return; Andrew M Morgan 18 If no swaps were necessary during an iteration, then the array is known to be sorted, and processing can stop further iterations would have no effect. 9

Additional Sort Algorithms There are many other sorting algorithms Several are more efficient than the algorithms shown here More efficient algorithms generally require the use of recursion We will talk about recursion much later in the semester Uses a divide-and-conquer algorithm Breaks large problems into smaller problems that are easy and fast to solve For those who are interested: The sorting algorithms presented here are O(n 2 More efficient algorithms run in (n log 2 n Andrew M Morgan 19 return (found; Andrew M Morgan 20 Finding An Element In An Unsorted Array If an array is unsorted, element to find could be anywhere in the array Logical way to search unsorted array Loop through nodes, comparing values, until found or end is reached Also works on sorted arrays Efficiency is O(n bool linearsearch( //true if found int elem, //val to look for //ary length const int iary[],//ary to search int &index //where found bool found; found = false; for (i = 0; i < numaryelems &&!found; i++ if (iary[i] == elem found = true; index = i; 10

Finding An Element In A Sorted Array Binary Search: Able to "ignore" half the array elements each iteration Efficiency: O(log 2 n bool binarysearch( int elem, const int iary[], int &index int endind; bool found; int midind; int startind; startind = 0; endind = numaryelems; found = false; //continued next column while (startind <= endind &&!found midind = (endind + startind / 2; if (elem == iary[midind] found = true; index = midind; else if (elem > iary[midind] startind = midind + 1; else //if (elem < iary[midind] endind = midind - 1; return (found; Andrew M Morgan 21 Analysis Of Search Algorithms Analysis done by searching a 500,000 element array for a nonexistent element, 50,000 times Linear Search Total Time: 248 seconds Elements Visited Per Search: 500,000 Total Elements Visited: 25,000,000,000 Binary Search Total Time: < 1 second Elements Visited Per Search: 18 Total Elements Visited: 900,000 Analysis done by searching a 500,000 element array for the element in the second position, 50,000 times Linear Search Total Time: < 1 second Elements Visited Per Search: 3 Total Elements Visited: 150,000 Binary Search Total Time: < 1 second Elements Visited Per Search: 17 Total Elements Visited: 850,000 Andrew M Morgan 22 11