LECTURE 17. Array Searching and Sorting

Similar documents
C/C++ Programming Lecture 18 Name:

Computers in Engineering COMP 208. Where s Waldo? Linear Search. Searching and Sorting Michael A. Hawker

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

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Chapter 10 - Notes Applications of Arrays

SORTING AND SEARCHING

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

Announcement. Submit assignment 3 on CourSys Do not hand in hard copy Due Friday, 15:20:00. Caution: Assignment 4 will be due next Wednesday

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

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

Downloaded from

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

Measuring algorithm efficiency

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

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

Elementary Sorting Algorithms

Computer Science & Engineering 150A Problem Solving Using Computers

Abstract Data Type: Stack

Lecture 6 Sorting and Searching

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

Data Structures and Algorithms for Engineers

KF5008 Algorithm Efficiency; Sorting and Searching Algorithms;

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

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

Quadratic: the time that it takes to sort an array is proportional to the. square of the number of elements.

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

1/ COP 3503 FALL 2012 SHAYAN JAVED LECTURE 16. Programming Fundamentals using Java

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

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

Sorting Pearson Education, Inc. All rights reserved.

CS Sorting Terms & Definitions. Comparing Sorting Algorithms. Bubble Sort. Bubble Sort: Graphical Trace

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

CS 115 Exam 3, Fall 2009

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

Introduction. Sorting. Definitions and Terminology: Program efficiency. Sorting Algorithm Analysis. 13. Sorting. 13. Sorting.

CSE101-lec#19. Array searching and sorting techniques. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Outline. What s wrong with Enumerations? Indexing Searching Self-Organizing Vectors Binary Searching Sorting Command line Arguments.

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

Searching & Sorting in Java Bubble Sort

Searching for Information. A Simple Method for Searching. Simple Searching. Class #21: Searching/Sorting I

Plan of the lecture. Quick-Sort. Partition of lists (or using extra workspace) Quick-Sort ( 10.2) Quick-Sort Tree. Partitioning arrays

Armstrong Atlantic State University Engineering Studies MATLAB Marina Sorting Primer

Search,Sort,Recursion

115 cs Algorithms and Data Structures-1. Sorting: To arrange the elements into ascending or descending order.

COMP1511 focuses on writing programs. Effciency is also important. Often need to consider:

CS 106 Introduction to Computer Science I

For loops, nested loops and scopes. Jordi Cortadella Department of Computer Science

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

Sorting Algorithms. + Analysis of the Sorting Algorithms

Outline. For loops, nested loops and scopes. Calculate x y. For loops. Scopes. Nested loops. Algorithm: repeated multiplication x x x x

Structured programming

Computer Science Foundation Exam

Solutions to Chapter 8

Searching. 11. Searching

Here we will only consider the problem of searching among the elements of an array. Intro Programming in C++

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

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

Arrays and Strings. Arash Rafiey. September 12, 2017

Arrays. Week 4. Assylbek Jumagaliyev

CS 115 Exam 3, Spring 2011

Analysis of Algorithms. CS 1037a Topic 13

Introduction to Computer Science Midterm 3 Fall, Points

COMP 250. Lecture 7. Sorting a List: bubble sort selection sort insertion sort. Sept. 22, 2017

Sorting. Bubble Sort. Selection Sort

Introduction. Sorting. Table of Contents

16.216: ECE Application Programming Spring 2015 Exam 2 Solution

Sorting and Searching

ECE 242 Data Structures and Algorithms. Simple Sorting I. Lecture 4. Prof.

Topic 14 Searching and Simple Sorts

CSE 2123 Sorting. Jeremy Morris

Outline. 14. Organization. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff

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

What is Recursion? ! Each problem is a smaller instance of itself. ! Implemented via functions. ! Very powerful solving technique.

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

C++ PROGRAMMING SKILLS Part 4: Arrays

Sorting. Weiss chapter , 8.6

Chapter 10. Sorting and Searching Algorithms. Fall 2017 CISC2200 Yanjun Li 1. Sorting. Given a set (container) of n elements

Binary Search and Worst-Case Analysis

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

(Refer Slide Time: 00:50)

Chapter 17: Sorting Algorithms. 1.1 Description Performance Example: Bubble Sort Bubble Sort Algorithm 5

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

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

CS 211: Binary Search and Sorting

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

Final: CSS 342 SAMPLE. Data Structures, Algorithms, and Discrete Mathematics I

Algorithm efficiency can be measured in terms of: Time Space Other resources such as processors, network packets, etc.

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

Problem solving paradigms

Lecture 11: In-Place Sorting and Loop Invariants 10:00 AM, Feb 16, 2018

Problems with simple variables

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

Esc101 Mid Semester Exam - II

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

CSCI 136 Data Structures & Advanced Programming. Lecture 9 Fall 2018 Instructors: Bills

Discussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage:

LECTURE 08 SEARCHING AND SORTING ARRAYS

What is sorting? Lecture 36: How can computation sort data in order for you? Why is sorting important? What is sorting? 11/30/10

Programming in OOP/C++

Sorting. CPSC 259: Data Structures and Algorithms for Electrical Engineers. Hassan Khosravi

Transcription:

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 arrays. In addition, we ll review some solutions to the array exercises from the previous array lecture.

SEARCHING Searching an array for a particular element is a common task that must be performed in computer programs. Two of the simplest, most common searching methods we ll cover are: Linear Search The most obvious and intuitive search mechanism. Looks through array elements one by one until the item is located. Takes longer than some specialized search techniques. Binary Search Depends on array being maintained in some sorted order. Looks at "middle" element, and decide which "side" of the array the element being searched for would have to be in. On each comparison, cuts number of possibilities in half. Runs much faster than linear search.

LINEAR SEARCH int LinearSearch(const int arr[], int size, int val) // search arr for the value (val), and return index where found, // return -1 if NOT found for (int i = 0; i < size; i++) // cout << " ** Loop iteration " << i+1 << "**\n"; if (arr[i] == val) return i; // if we just found it, return the index // We didn't find it while running loop. So now return the "not // found" indication return -1;

BINARY SEARCH int BinarySearch(const int arr[], int size, int val) int low = 0; // track current low index int high = size-1; // track current high index int mid; // for computing midpoint while (low <= high) // while the indices are still in order mid = (low + high) / 2; // compute midpoint of current range if (arr[mid] == val) // if found, return index where found return mid; else if (val < arr[mid]) // value is in low half high = mid - 1; else // (val is bigger, so in top half) low = mid + 1; return -1; // wasn't found

SORTING Another common array task is to sort arrays. Two common sorting methods that we ll study are: Bubble Sort Compares side-by-side elements. If out of order, swap them. Uses nested loops. Each run through inner loop "bubbles" one element to the end, its final position. Outer loop must run size-1 times. Selection Sort Also uses nested loops. Run through inner loop "selects" the largest (or smallest) element of the remaining items (i.e. the ones that are not yet in position), and swaps it with the end element. Outer loop must run size-1 times.

BUBBLE SORT void BubbleSort(int arr[], int size) for (int j = 0; j < size - 1; j++) // run process size-1 times // this loop will "bubble" the high value to the top for (int i = 0; i < size-1-j; i++) if (arr[i] > arr[i+1]) // if this one is bigger than his neighbor // swap them int temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp;

SELECTION SORT void SelectionSort(int arr[], int size) int smallindex; for (int j = 0; j < size - 1; j++) // run process size-1 times // find smallest element (from index j upwards) smallindex = j; for (int i = j; i < size; i++) if (arr[i] < arr[smallindex]) smallindex = i; // swap with slot j int temp = arr[j]; arr[j] = arr[smallindex]; arr[smallindex] = temp;

CODE EXAMPLES searchsort.cpp

EXERCISES A function called Sum that takes in an array of type double and returns the sum of its elements. A function called Average that takes in an integer array and returns the average of it's elements (as a double). A function called Reverse that takes in an integer array and reverses its contents. A function called Sort that takes in an array of integers and sorts its contents in ascending order. A function called Minimum that takes in an array of type double and returns the smallest number in the array.

SUM int Sum(const int arr[], const int size) int total = 0; for (int i = 0; i < size; i++) total = total + arr[i]; return total;

AVERAGE double Average(const int arr[], const int size) return Sum(arr, size) * 1.0 / size;

REVERSE void Reverse(int arr[], int size) int temp, i; for (i = 0; i < size/2; i++) temp = arr[size-i-1]; arr[size-i-1] = arr[i]; arr[i] = temp;

SORT Just use BubbleSort or SelectionSort functions!

MINIMUM double Minimum(const double arr[], const int size) double min = arr[0]; // the answer SO FAR for (int i = 1; i < size; i++) if (arr[i] < min) min = arr[i]; return min; // largest number