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

Size: px
Start display at page:

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

Transcription

1 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

2 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 min; Andrew M Morgan 4 2

3 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

4 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 Array element to be swapped with minimum Array element containing minimum value Selection Sort Algorithm Andrew M Morgan 7 Final Sorted Array 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

5 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

6 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 X 2 4 X X X X X X X 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

7 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

8 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: Num Compares: Num Swaps: Total Time : 11 Num Swaps: Bubble Sort Analysis Output Total Time : 10 Num Ary Elems: Num Compares: Num Swaps: Total Time : 37 Num Swaps: 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: Num Compares: Num Swaps: Bubble Sort Analysis Output Total Time : 3 Num Ary Elems: Num Compares: Num Swaps: Total Time : 12 Num Swaps: Total Time : 14 Num Swaps: Total Time : 45 Num Ary Elems: Num Compares: Num Swaps: Total Time : 57 Num Ary Elems: Num Compares: Num Swaps: Andrew M Morgan 16 8

9 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: Bubble Sort Analysis Total Time : 15 Num Swaps: Modified Bubble Sort Analysis Total Time : 0 Num Compares: Num Swaps: 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

10 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

11 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

Chapter 10 - Notes Applications of Arrays

Chapter 10 - Notes Applications of Arrays Chapter - Notes Applications of Arrays I. List Processing A. Definition: List - A set of values of the same data type. B. Lists and Arrays 1. A convenient way to store a list is in an array, probably a

More information

C/C++ Programming Lecture 18 Name:

C/C++ Programming Lecture 18 Name: . The following is the textbook's code for a linear search on an unsorted array. //***************************************************************** // The searchlist function performs a linear search

More information

LECTURE 17. Array Searching and Sorting

LECTURE 17. Array Searching and Sorting LECTURE 17 Array Searching and Sorting ARRAY SEARCHING AND SORTING Today we ll be covering some of the more common ways for searching through an array to find an item, as well as some common ways to sort

More information

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

Ch 8. Searching and Sorting Arrays Part 1. Definitions of Search and Sort Ch 8. Searching and Sorting Arrays Part 1 CS 2308 Fall 2011 Jill Seaman Lecture 1 1 Definitions of Search and Sort! Search: find an item in an array, return the index to the item, or -1 if not found.!

More information

! 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.

! 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. Searching & Sorting Week 11 Gaddis: 8, 19.6,19.8 CS 5301 Spring 2015 Jill Seaman 1 Definitions of Search and Sort! Search: find a given item in a list, return the position of the item, or -1 if not found.!

More information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #22, More Graph Searches, Some Sorting, and Efficient Sorting Algorithms John Ridgway April 21, 2015 1 Review of Uniform-cost Search Uniform-Cost

More information

! 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.

! 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. Searching & Sorting Week 11 Gaddis: 8, 19.6,19.8 CS 5301 Fall 2014 Jill Seaman 1 Definitions of Search and Sort! Search: find a given item in a list, return the position of the item, or -1 if not found.!

More information

CS 115 Exam 3, Fall 2009

CS 115 Exam 3, Fall 2009 CS115Exam3,Fall2009 Yourname: Rules Youmustbrieflyexplainyouranswerstoreceivepartialcredit. Whenasnippetofcodeisgiventoyou,youcanassume o thatthecodeisenclosedwithinsomefunction,evenifnofunction definitionisshown

More information

! 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.

! 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. Searching & Sorting Week 11 Gaddis: 8, 19.6,19.8 (8th ed) Gaddis: 8, 20.6,20.8 (9th ed) CS 5301 Fall 2018 Jill Seaman!1 Definitions of Search and Sort! Search: find a given item in a list, return the position

More information

Sorting and Searching Algorithms

Sorting and Searching Algorithms Sorting and Searching Algorithms Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale tessema.mengistu@siu.edu Room - Faner 3131 1 Outline Introduction to Sorting

More information

Solutions to Chapter 8

Solutions to Chapter 8 Solutions to Chapter 8 Review Questions 1. a. True 3. b. False 5. b. False 7. c. index 9. d. ary[0] = x; 11. e. sorting 13. e. sequential 15. a. A two-dimensional array can be thought of as an array of

More information

SORTING AND SEARCHING

SORTING AND SEARCHING SORTING AND SEARCHING Today Last time we considered a simple approach to sorting a list of objects. This lecture will look at another approach to sorting. We will also consider how one searches through

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

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

! Search: find an item in an array, return the. ! Sort: rearrange the items in an array into some. ! There are various methods (algorithms) for Ch 8. earching and orting Arrays 8.1 and 8.3 only C 2308 pring 2013 Jill eaman efinitions of earch and ort! earch: find an item in an array, return the index to the item, or -1 if not found.! ort: rearrange

More information

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

The University Of Michigan. EECS402 Lecture 05. Andrew M. Morgan. Savitch Ch. 5 Arrays Multi-Dimensional Arrays. Consider This Program The University Of Michigan Lecture 05 Andrew M. Morgan Savitch Ch. 5 Arrays Multi-Dimensional Arrays Consider This Program Write a program to input 3 ints and output each value and their sum, formatted

More information

Chapter 10 Sorting and Searching Algorithms

Chapter 10 Sorting and Searching Algorithms Chapter Sorting and Searching Algorithms Sorting rearranges the elements into either ascending or descending order within the array. (We ll use ascending order.) The values stored in an array have keys

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 0-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

C++ PROGRAMMING SKILLS Part 4: Arrays

C++ PROGRAMMING SKILLS Part 4: Arrays C++ PROGRAMMING SKILLS Part 4: Arrays Outline Introduction to Arrays Declaring and Initializing Arrays Examples Using Arrays Sorting Arrays: Bubble Sort Passing Arrays to Functions Computing Mean, Median

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 11 / 2015 Instructor: Michael Eckmann Today s Topics Comments and/or Questions? Sorting Searching Michael Eckmann - Skidmore College - CS 106 - Summer 2015

More information

Algorithm Analysis. Performance Factors

Algorithm Analysis. Performance Factors Algorithm Analysis How can we demonstrate that one algorithm is superior to another without being misled by any of the following problems: Special cases Every algorithm has certain inputs that allow it

More information

Module 08: Searching and Sorting Algorithms

Module 08: Searching and Sorting Algorithms Module 08: Searching and Sorting Algorithms Topics: Searching algorithms Sorting algorithms 1 Application: Searching a list Suppose you have a list L. How could you determine if a particular value is in

More information

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

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return 0. How would we write the BinaryHeap siftdown function recursively? [0] 6 [1] [] 15 10 Name: template class BinaryHeap { private: int maxsize; int numitems; T * heap;... [3] [4] [5] [6] 114 0

More information

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

Chapter Objectives. List Processing. Chapter 10: Applications of Arrays and Strings. Java Programming: Program Design Including Data Structures Chapter 10: Applications of Arrays and Strings Java Programming: Program Design Including Data Structures Chapter Objectives Learn how to implement the sequential search algorithm Explore how to sort an

More information

Data Types. Operators, Assignment, Output and Return Statements

Data Types. Operators, Assignment, Output and Return Statements Pseudocode Reference Sheet rev 4/17 jbo Note: This document has been developed by WeTeach_CS, and is solely based on current study materials and practice tests provided on the TEA website. An official

More information

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

Sorting. Task Description. Selection Sort. Should we worry about speed? Sorting Should we worry about speed? Task Description We have an array of n values in any order We need to have the array sorted in ascending or descending order of values 2 Selection Sort Select the smallest

More information

Arrays and Applications

Arrays and Applications Arrays and Applications 60-141: Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2014 Instructor: Dr. Asish Mukhopadhyay What s an array Let a 0, a 1,, a n-1 be a sequence

More information

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

CS 12 Fall 2003 Solutions for mid-term exam #2 CS 12 Fall 2003 Solutions for mid-term exam #2 1. (10 points) Compilers and interpreters Provide short answers (a few sentences at most) to the following questions. (a) What is the difference between a

More information

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

Topics. Sorting. Sorting. 1) How can we sort data in an array? a) Selection Sort b) Insertion Sort Topics 1) How can we sort data in an array? a) Selection Sort b) Insertion Sort 2) How can we search for an element in an array? a) Linear Search b) Binary Search Slides #15 Sections 9.1-9.5 Sorting and

More information

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

Sorting Algorithms. Array Data is being arranged in ascending order using the bubble sort algorithm. #1 #2 #3 #4 #5 #6 #7 Sorting Algorithms One of the fundamental problems of computer science is ordering a list of items. There s a plethora of solutions to this problem, known as sorting algorithms. Some sorting algorithms

More information

EECS402 Lecture 02. Functions. Function Prototype

EECS402 Lecture 02. Functions. Function Prototype The University Of Michigan Lecture 02 Andrew M. Morgan Savitch Ch. 3-4 Functions Value and Reference Parameters Andrew M. Morgan 1 Functions Allows for modular programming Write the function once, call

More information

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

Searching Elements in an Array: Linear and Binary Search. Spring Semester 2007 Programming and Data Structure 1 Searching Elements in an Array: Linear and Binary Search Spring Semester 2007 Programming and Data Structure 1 Searching Check if a given element (called key) occurs in the array. Example: array of student

More information

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

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information

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

Bubble sort starts with very first two elements, comparing them to check which one is greater. Bubble Sorting: Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they

More information

Introduction to Computer Science Midterm 3 Fall, Points

Introduction to Computer Science Midterm 3 Fall, Points Introduction to Computer Science Fall, 2001 100 Points Notes 1. Tear off this sheet and use it to keep your answers covered at all times. 2. Turn the exam over and write your name next to the staple. Do

More information

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

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 Looking for something COMP 10 EXPLORING COMPUTER SCIENCE Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE Searching algorithms Linear search Complexity Sorting algorithms

More information

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) Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8

More information

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

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information

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

Linear Search. Sorting Algorithms. linear search code. Sorting in Ascending Order Selection Sort. Selection sort algorithm Linear Search Additional CPSC1620 topics Searching, Sorting, Big(O) template functions, classes The idea of a linear search is to walk through the entire list until the value is found. The list does not

More information

Walls & Mirrors Chapter 9. Algorithm Efficiency and Sorting

Walls & Mirrors Chapter 9. Algorithm Efficiency and Sorting Walls & Mirrors Chapter 9 Algorithm Efficiency and Sorting The Execution Time of Algorithms Counting an algorithm s operations int sum = item[0]; int j = 1; while (j < n) { sum += item[j]; ++j; }

More information

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/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO? 8/5/10 TODAY'S OUTLINE Recursion COMP 10 EXPLORING COMPUTER SCIENCE Revisit search and sorting using recursion Binary search Merge sort Lecture 8 Recursion WHAT DOES THIS CODE DO? A function is recursive

More information

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

8.1. Chapter 8: Introduction to Search Algorithms. Linear Search. Linear Search. Linear Search - Example 8/23/2014. Introduction to Search Algorithms Chapter 8: Searching and Sorting Arrays 8.1 Introduction to Search Algorithms Introduction to Search Algorithms Search: locate an item in a list of information Two algorithms we will examine: Linear search

More information

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

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters. The University Of Michigan Lecture 02 Andrew M. Morgan Savitch Ch. 3-4 Functions Value and Reference Parameters Andrew M. Morgan 1 Functions Allows for modular programming Write the function once, call

More information

Ch 5-2. Arrays Part 2

Ch 5-2. Arrays Part 2 2014-1 Ch 5-2. Arrays Part 2 March 29, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497; Fax : +82-53-810-4742

More information

Lecture 6 Sorting and Searching

Lecture 6 Sorting and Searching Lecture 6 Sorting and Searching Sorting takes an unordered collection and makes it an ordered one. 1 2 3 4 5 6 77 42 35 12 101 5 1 2 3 4 5 6 5 12 35 42 77 101 There are many algorithms for sorting a list

More information

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

Topics Applications Most Common Methods Serial Search Binary Search Search by Hashing (next lecture) Run-Time Analysis Average-time analysis Time anal CSC212 Data Structure t Lecture 18 Searching Instructor: George Wolberg Department of Computer Science City College of New York @ George Wolberg, 2016 1 Topics Applications Most Common Methods Serial Search

More information

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

Recursive Algorithms. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Recursive Algorithms CS 180 Sunil Prabhakar Department of Computer Science Purdue University Recursive Algorithms Within a given method, we are allowed to call other accessible methods. It is also possible

More information

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

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of

More information

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

CS150 Intro to CS I. Fall Fall 2017 CS150 - Intro to CS I 1 CS150 Intro to CS I Fall 2017 Fall 2017 CS150 - Intro to CS I 1 Chapter 4 Making Decisions Reading: Chapter 3 (3.5 pp. 101), Chapter 4 (4.4 pp. 166-168; 4.5 pp. 169-175; 4.6 pp.176-181; 4.8 pp. 182-189;

More information

LECTURE 08 SEARCHING AND SORTING ARRAYS

LECTURE 08 SEARCHING AND SORTING ARRAYS PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 08 SEARCHING AND

More information

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

Fundamental problem in computing science. putting a collection of items in order. Often used as part of another algorithm cmpt-225 Sorting Sorting Fundamental problem in computing science putting a collection of items in order Often used as part of another algorithm e.g. sort a list, then do many binary searches e.g. looking

More information

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

There are two possible results from a search: either you find the item you are looking for, or you don't. 1 Programming with C Terry Marris December 2010 16 Searching and Sorting In the previous chapter we looked at s of numbers. Now we see how to search through an and how to sort the contents of an into order.

More information

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

for (int outercounter = nums.length - 1; outercounter > 0 && swappedthatturn; outercounter -- /* * A small set of sorting algorithms, written in Java and C++ * Note that they are written by a C++ beginner, may contain mistakes * Or bad habits that have to be avoided * @author Kadir Can Çelik */

More information

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

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter What you will learn from Lab 7 In this laboratory, you will understand how to use typical function prototype with

More information

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

Sorting/Searching and File I/O. Sorting Searching Reading for this lecture: L&L Sorting/Searching and File I/O Sorting Searching Reading for this lecture: L&L 10.4-10.5 1 Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based

More information

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

Sorting. Sorting. Stable Sorting. In-place Sort. Bubble Sort. Bubble Sort. Selection (Tournament) Heapsort (Smoothsort) Mergesort Quicksort Bogosort Principles of Imperative Computation V. Adamchik CS 15-1 Lecture Carnegie Mellon University Sorting Sorting Sorting is ordering a list of objects. comparison non-comparison Hoare Knuth Bubble (Shell, Gnome)

More information

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

12/1/2016. Sorting. Savitch Chapter 7.4. Why sort. Easier to search (binary search) Sorting used as a step in many algorithms Sorting Savitch Chapter. Why sort Easier to search (binary search) Sorting used as a step in many algorithms Sorting algorithms There are many algorithms for sorting: Selection sort Insertion sort Bubble

More information

CSE 2123 Sorting. Jeremy Morris

CSE 2123 Sorting. Jeremy Morris CSE 2123 Sorting Jeremy Morris 1 Problem Specification: Sorting Given a list of values, put them in some kind of sorted order Need to know: Which order? Increasing? Decreasing? What does sorted order mean?

More information

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

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type. CS 7A - Fall 2016 - Midterm 1 10/20/16 Write responses to questions 1 and 2 on this paper or attach additional sheets, as necessary For all subsequent problems, use separate paper Do not use a computer

More information

Data Structures Lecture 3 Order Notation and Recursion

Data Structures Lecture 3 Order Notation and Recursion Data Structures Lecture 3 Order Notation and Recursion 1 Overview The median grade.cpp program from Lecture 2 and background on constructing and using vectors. Algorithm analysis; order notation Recursion

More information

Week 3: Pointers (Part 2)

Week 3: Pointers (Part 2) Advanced Programming (BETC 1353) Week 3: Pointers (Part 2) Dr. Abdul Kadir abdulkadir@utem.edu.my Learning Outcomes: Able to describe the concept of pointer expression and pointer arithmetic Able to explain

More information

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)

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) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

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

Learning Recursion. Recursion [ Why is it important?] ~7 easy marks in Exam Paper. Step 1. Understand Code. Step 2. Understand Execution Recursion [ Why is it important?] ~7 easy marks in Exam Paper Seemingly Different Coding Approach In Fact: Strengthen Top-down Thinking Get Mature in - Setting parameters - Function calls - return + work

More information

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

Administrivia. HW on recursive lists due on Wednesday. Reading for Wednesday: Chapter 9 thru Quicksort (pp ) Sorting 4/23/18 Administrivia HW on recursive lists due on Wednesday Reading for Wednesday: Chapter 9 thru Quicksort (pp. 271-284) A common problem: Sorting Have collection of objects (numbers, strings,

More information

Searching and Sorting

Searching and Sorting Searching and Sorting Sequential search sequential search: Locates a target value in an array/list by examining each element from start to finish. How many elements will it need to examine? Example: Searching

More information

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

Sorting is ordering a list of objects. Here are some sorting algorithms Sorting Sorting is ordering a list of objects. Here are some sorting algorithms Bubble sort Insertion sort Selection sort Mergesort Question: What is the lower bound for all sorting algorithms? Algorithms

More information

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

To become familiar with array manipulation, searching, and sorting. ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation,

More information

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

Component 02. Algorithms and programming. Sorting Algorithms and Searching Algorithms. Matthew Robinson Component 02 Algorithms and programming Sorting Algorithms and Searching Algorithms 1 BUBBLE SORT Bubble sort is a brute force and iterative sorting algorithm where each adjacent item in the array is compared.

More information

CS 315 Data Structures mid-term 2

CS 315 Data Structures mid-term 2 CS 315 Data Structures mid-term 2 1) Shown below is an AVL tree T. Nov 14, 2012 Solutions to OPEN BOOK section. (a) Suggest a key whose insertion does not require any rotation. 18 (b) Suggest a key, if

More information

Fun facts about recursion

Fun facts about recursion Outline examples of recursion principles of recursion review: recursive linked list methods binary search more examples of recursion problem solving using recursion 1 Fun facts about recursion every loop

More information

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

Sol. Sol. a. void remove_items_less_than(int arr[], int size, int value) #include <iostream> #include <ctime> using namespace std; r6.14 For the operations on partially filled arrays below, provide the header of a func tion. d. Remove all elements that are less than a given value. Sol a. void remove_items_less_than(int arr[], int

More information

Sorting and Searching

Sorting and Searching Sorting and Searching Sorting o Simple: Selection Sort and Insertion Sort o Efficient: Quick Sort and Merge Sort Searching o Linear o Binary Reading for this lecture: http://introcs.cs.princeton.edu/python/42sort/

More information

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

10/21/ Linear Search The linearsearch Algorithm Binary Search The binarysearch Algorithm 13.1 Linear Search! A linear search simply examines each item in the search pool, one at a time, until either the target is found or until the pool is exhausted! This approach does not assume the items

More information

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

106B Final Review Session. Slides by Sierra Kaplan-Nelson and Kensen Shi Livestream managed by Jeffrey Barratt 106B Final Review Session Slides by Sierra Kaplan-Nelson and Kensen Shi Livestream managed by Jeffrey Barratt Topics to Cover Sorting Searching Heaps and Trees Graphs (with Recursive Backtracking) Inheritance

More information

Final Exam Solutions PIC 10B, Spring 2016

Final Exam Solutions PIC 10B, Spring 2016 Final Exam Solutions PIC 10B, Spring 2016 Problem 1. (10 pts) Consider the Fraction class, whose partial declaration was given by 1 class Fraction { 2 public : 3 Fraction ( int num, int den ); 4... 5 int

More information

Searching and Sorting

Searching and Sorting CS 211 SEARCH & SORT SEARCHING & SORTING Searching and Sorting Searching means that we have some collection of data, and we seek a particular value that might be contained within our collection. We provide

More information

Sorting: Overview/Questions

Sorting: Overview/Questions CS121: Sorting and Searching Algorithms John Magee 24 April 2012 1 Sorting: Overview/Questions What is sorting? Why does sorting matter? How is sorting accomplished? Why are there different sorting algorithms?

More information

Introduction to Computers and Programming

Introduction to Computers and Programming 16.070 Introduction to Computers and Programming April 11 Recitation 9 Spring 2002 Topics: Function Review Sorting and Searching Recursion Big O Notation Serial I/O Other Function Review f(x) = (x) f =

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 06 - Stephen Scott Adapted from Christopher M. Bourke 1 / 30 Fall 2009 Chapter 8 8.1 Declaring and 8.2 Array Subscripts 8.3 Using

More information

Introduction to Computers and Programming. Today

Introduction to Computers and Programming. Today Introduction to Computers and Programming Prof. I. K. Lundqvist Lecture 10 April 8 2004 Today How to determine Big-O Compare data structures and algorithms Sorting algorithms 2 How to determine Big-O Partition

More information

Searching & Sorting in Java Bubble Sort

Searching & Sorting in Java Bubble Sort With the bubble sort, the basic idea is to compare adjacent values and exchange them if they are not in order. Consider the following example which shows the first pass through the algorithm. 1. Compare

More information

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

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables 1 6 C Arrays 6.2 Arrays 2 Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name + position number arrayname[ position number ] First element at position

More information

Sorting Algorithms. Biostatistics 615 Lecture 7

Sorting Algorithms. Biostatistics 615 Lecture 7 Sorting Algorithms Biostatistics 615 Lecture 7 Last Week Recursive Functions Natural expression for many algorithms Dynamic Programming Automatic way to generate efficient versions of recursive algorithms

More information

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

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators) Name: Email address: Quiz Section: CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators) Instructions: Read the directions for each question carefully before answering. We will

More information

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

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 13 Recursion Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Recursive void Functions Tracing recursive calls Infinite recursion, overflows Recursive Functions that Return

More information

QuickSort. CIS 15 : Spring 2007

QuickSort. CIS 15 : Spring 2007 QuickSort CIS 15 : Spring 2007 Functionalia TEA! HW 1 is DUE FRIDAY 23rd, 11:59 PM Do the BASIC Program First! Turn in Basic Program and Challenges Seperately Today: Binary Search Example QuickSort Submitting

More information

CS 310 Advanced Data Structures and Algorithms

CS 310 Advanced Data Structures and Algorithms CS 310 Advanced Data Structures and Algorithms Sorting June 13, 2017 Tong Wang UMass Boston CS 310 June 13, 2017 1 / 42 Sorting One of the most fundamental problems in CS Input: a series of elements with

More information

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

SCJ2013 Data Structure & Algorithms. Bubble Sort. Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi SCJ2013 Data Structure & Algorithms Bubble Sort Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi 1 Bubble Sort Sorting activities for Bubble: Go through multiple passes over the array. In every pass: Compare

More information

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

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge Trees & Heaps Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Fall 2018 Jill Seaman!1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every

More information

Priority queues. Priority queues. Priority queue operations

Priority queues. Priority queues. Priority queue operations Priority queues March 30, 018 1 Priority queues The ADT priority queue stores arbitrary objects with priorities. An object with the highest priority gets served first. Objects with priorities are defined

More information

CHAPTER 7 Iris Hui-Ru Jiang Fall 2008

CHAPTER 7 Iris Hui-Ru Jiang Fall 2008 CHAPTER 7 SORTING Iris Hui-Ru Jiang Fall 2008 2 Contents Comparison sort Bubble sort Selection sort Insertion sort Merge sort Quick sort Heap sort Introspective sort (Introsort) Readings Chapter 7 The

More information

Search Lesson Outline

Search Lesson Outline 1. Searching Lesson Outline 2. How to Find a Value in an Array? 3. Linear Search 4. Linear Search Code 5. Linear Search Example #1 6. Linear Search Example #2 7. Linear Search Example #3 8. Linear Search

More information

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

Today. CISC101 Reminders & Notes. Searching in Python - Cont. Searching in Python. From last time CISC101 Reminders & Notes Test 3 this week in tutorial USATs at the beginning of next lecture Please attend and fill out an evaluation School of Computing First Year Information Session Thursday, March

More information

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

Algorithms. Chapter 8. Objectives After studying this chapter, students should be able to: Objectives After studying this chapter, students should be able to: Chapter 8 Algorithms Define an algorithm and relate it to problem solving. Define three construct and describe their use in algorithms.

More information

What is an algorithm?

What is an algorithm? Announcements CS 142 C++ Pointers Reminder Program 6 due Sunday, Nov. 9 th by 11:55pm 11/3/2014 2 Pointers and the Address Operator Pointer Variables Each variable in a program is stored at a unique address

More information

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

DATA STRUCTURES AND ALGORITHMS. Sorting algorithms (insertion sort, bubble sort, selection sort) DATA STRUCTURES AND ALGORITHMS Sorting algorithms (insertion sort, bubble sort, selection sort) Summary of the previous lecture Recursion Definition Examples Factorial Fibonacci Hanoi tower Printing of

More information

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

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd El-Shorouk Academy Acad. Year : 2013 / 2014 High Institute of Computer Science & Information Technology Term : 1 st Year : 2 nd Computer Science Department Object Oriented Programming Section (1) Arrays

More information

Lecture 19 Sorting Goodrich, Tamassia

Lecture 19 Sorting Goodrich, Tamassia Lecture 19 Sorting 7 2 9 4 2 4 7 9 7 2 2 7 9 4 4 9 7 7 2 2 9 9 4 4 2004 Goodrich, Tamassia Outline Review 3 simple sorting algorithms: 1. selection Sort (in previous course) 2. insertion Sort (in previous

More information

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

CSCI 136 Data Structures & Advanced Programming. Lecture 12 Fall 2018 Profs Bill & Jon CSCI 136 Data Structures & Advanced Programming Lecture 12 Fall 2018 Profs Bill & Jon Last Time Assertions SLL Improvements Tail pointers Circularly Linked Lists Doubly Linked Lists Practice with recursion

More information

Sorting and Searching. Sudeshna Sarkar 7 th Feb 2017

Sorting and Searching. Sudeshna Sarkar 7 th Feb 2017 Sorting and Searching Sudeshna Sarkar 7 th Feb 2017 Searching an Array: Linear and Binary Search Spring 2012 Programming and Data Structure 2 Searching Check if a given element (key) occurs in the array.

More information

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

1. Write step by step code to delete element from existing Doubly Linked List. Suppose that all declarations are done 1. Write step by step code to delete element from existing Doubly Linked List. Suppose that all declarations are done. first NULL 42 A A 13 A A 6 NULL Write code here first NULL 42 A A 13 A A 6 NULL p

More information