Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.

Slides:



Advertisements
Similar presentations
Lesson 8 Searching and Sorting Arrays 1CS 1 Lesson 8 -- John Cole.
Advertisements

Garfield AP Computer Science
CSE Lecture 3 – Algorithms I
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 9: Searching, Sorting, and Algorithm Analysis
Visual C++ Programming: Concepts and Projects
Cmpt-225 Sorting. Fundamental problem in computing science  putting a collection of items in order Often used as part of another algorithm  e.g. sort.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Algorithm Efficiency and Sorting
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Searching and Sorting Arrays
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Searching and Sorting Arrays.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
UNIT 18 Searching and Sorting.
Lecture 5 Searching and Sorting Richard Gesick. The focus Searching - examining the contents of the array to see if an element exists within the array.
Computer Science Searching & Sorting.
Chapter 8 Searching and Sorting Arrays Csc 125 Introduction to C++ Fall 2005.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
Examples using Arrays. Summing Squares Problem: To compute the sum of the squares of N numbers N is given N values are also given These should be read.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
CSC 211 Data Structures Lecture 13
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
LAB#6. 2 Overview Before we go to our lesson we must know about : 1. data structure. 2.Algorithms. data structure is an arrangement of data in a computer.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
3 – SIMPLE SORTING ALGORITHMS
Sorting and Searching. Selection Sort  “Search-and-Swap” algorithm 1) Find the smallest element in the array and exchange it with a[0], the first element.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Selection Sort Sorts an array by repeatedly finding the smallest.
UNIT 5.  The related activities of sorting, searching and merging are central to many computer applications.  Sorting and merging provide us with a.
Lecture No. 04,05 Sorting.  A process that organizes a collection of data into either ascending or descending order.  Can be used as a first step for.
Sorting and Searching by Dr P.Padmanabham Professor (CSE)&Director
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
1 Principles of Computer Science I Honors Section Note Set 5 CSE 1341.
SORTING ALGORITHMS King Saud University College of Applied studies and Community Service CSC 1101 By: Nada Alhirabi 1.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Searching Topics Sequential Search Binary Search.
CSE 143 Lecture 16 Sorting reading: 13.1, slides created by Marty Stepp
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 1 Simple Searching Many.
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
Searching and Sorting Searching algorithms with simple arrays
Searching and Sorting Arrays
Searching and Sorting Algorithms
Lecture 14 Searching and Sorting Richard Gesick.
Introduction to Search Algorithms
Searching & Sorting "There's nothing hidden in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The Sorting.
Topic 14 Searching and Simple Sorts
CSc 110, Spring 2017 Lecture 39: searching.
Lecture 11 Searching and Sorting Richard Gesick.
Searching and Sorting Arrays
Standard Version of Starting Out with C++, 4th Edition
Search,Sort,Recursion.
Topic 14 Searching and Simple Sorts
Principles of Computing – UFCFA3-30-1
Searching and Sorting Arrays
Searching and Sorting Arrays
Principles of Computing – UFCFA3-30-1
Module 8 – Searching & Sorting Algorithms
Presentation transcript:

Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham

Week 11 Topics Sorting: selection, insertion and bubble sort Profiling the Selection Sort Algorithm Analyzing the Performance of the Selection Sort Algorithm Searching Binary Search

Sorting A sorting algorithm rearranges the elements of a collection so that they are stored in sorted order A collection can be sorted in ascending order (from low to high) or in descending order (from high to low) There are many algorithms for sorting, the most common introductory ones are the selection, insertion and bubble sorts

Sorting Cont. (selection) The selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled, working from “left to right” A selection sort is a simple algorithm and is easy to implement A selection sort is inefficient for large lists

Sorting Cont. (selection) The selection sort is a comparison sort that works as follows: –Find the minimum value in the list –Swap it with the value in the first position –Sort the remainder of the list (excluding the first value) The next value to “the right” becomes the new beginning of the unsorted section of the list and the algorithm above is repeated for the unsorted section until every element in the list (except the last element) is compared (source: Wikipedia)

Sorting Cont. (selection) Initial state Begin first pass Begin second pass Min value for pass 1 is: 5 Min value for pass 2 is: 9

Sorting Cont. (selection) Begin third pass Begin fourth pass Collection is now selection sorted in ascending order. Min value for pass 4 is: 12 Min value for pass 3 is: Final state

Sorting Cont. (selection) // SELECTION SORT public static int [ ] selSort(int arr[ ], int left, int right) { // left is beginning of unsorted section for (int i = left; i < right; ++i) { int min = i; for (int j = i; j < right; ++j) // find the min element if (arr[min] > arr[j]) min = j; // swap the minimum element int temp = arr[min]; arr[min] = arr[i]; arr[i] = temp; { return arr; }

Sorting Cont. (insertion) An insertion sort works by choosing the next unsorted element and finding where to insert it in the sorted section. When the location is found it then shifts elements to the right and drops the element into place. An insertion sort is a simple algorithm and is easy to implement An insertion sort is inefficient for large lists, but is somewhat more efficient than a selection or a bubble sort

Sorting Cont. (insertion) The insertion sort is a comparison sort that works as follows: –Start with the second element in the list as the target –Compare the target to the first element, if target is smaller in value, slide the first element to the “right” and put the value of the target into the first element The third element then becomes the target, and again you “work backwards”, comparing target to element two then one if necessary. At the point target is greater than element to the left, push previous larger elements to the right and put target value in that position. Continue in like with next element to the right until all elements are “targeted”.

Sorting Cont. (insertion) Initial state Begin first pass Begin second pass 1st pass begins at pos 2 2nd pass begins at pos 3

Sorting Cont. (insertion) Begin third pass Begin fourth pass Collection is now insertion sorted in ascending order. 4th pass begins at pos 5 3rd pass begins at pos Final state

Sorting Cont. (insertion) // INSERTION SORT public static int [ ] insSort(int arr[ ], int left, int right) { for (int i = left+1; j < right; ++i) { int j, val = arr[i]; // locate position to place target element for ( j= i-1; j >= left && arr[j] > val; --j) arr[j+1] = arr[j]; // slide each element to the right arr[j+1] = val; // drop element into position } return arr; }

Sorting Cont. (bubble) The bubble sort (also called the exchange sort) works by repeatedly stepping through the list to be sorted, comparing two items at a time, swapping these two items if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which means the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top (i.e. head) of the list via the swaps. The bubble sort is a simple algorithm and is easy to implement, but is inefficient for large lists

Sorting Cont. (bubble) The bubble sort is a comparison sort that works as follows (source - Wikipedia): –Compare adjacent elements. If the first is greater than the second, swap them. –Do this for each pair of adjacent elements, starting with the first two and ending with the last two. At this point the last element should be the greatest. –Repeat the steps for all elements except the last one. –Keep repeating for one fewer element each time, until you have no more pairs to compare.

Sorting Cont. (bubble) Initial state Begin first pass Begin second pass 1st pass compare pattern: 2nd pass compare pattern:

Sorting Cont. (bubble) Begin forth pass Final state Collection is now bubble sorted in ascending order. 4th pass compare pattern: Begin third pass 3rd pass compare pattern:

Sorting Cont. (bubble) // BUBBLE SORT public static void bubbleSort(int data[ ]) { boolean isSorted; int tempVar; int passes = 0; do { isSorted = true; for (int i = 1; i < data.length - passes; i++) { if (data[i] < data[i - 1]) { // swap logic tempVar = data[i]; data[i] = data[i - 1]; data[i - 1] = tempVar; isSorted = false; } } passes++; } while (!isSorted); // continue if a swap took place }

Profiling the Selection Sort Algorithm An important aspect of studying algorithms is to determine the complexity of a given algorithm Complexity in computer science is usually measured two ways: space complexity and time complexity Space complexity is a measure of the amount of memory an algorithm takes in its execution, while time complexity is a measure of the amount of time an algorithm takes in its execution

Profiling the Selection Sort Algorithm Cont. Often an inverse relationship exists: time can be reduced if space is increased, and vice-versa Determining the complexity of an algorithm can be done two ways: mathematical analysis (covered in the next section) and profiling Profiling is the process of gathering runtime statistics about programs, such as execution time, memory usage, and method call counts

Profiling the Selection Sort Algorithm Cont. ElementsBubbleSelectionInsertion 2, , ,4801, ,92031,39114,0479,125 Sort time in milliseconds for various array sizes The interesting characteristic of this data is that for each of the sorting algorithms, as the number of elements doubles, the sorting time roughly quadruples

Analyzing the Performance of the Selection Sort Algorithm To do a selection sort requires finding the smallest value (up to n visits) and then swapping the elements (two visits). The algorithm can be expressed as the equation: 1/2 n² + 5/2 n - 3 The above can be reduced to the fastest growing term n² Thus the selection sort using big-Oh notation is called an O(n²) algorithm. Doubling the data set means a fourfold increase in processing time.

Searching To find a value in an unordered collection you must use a linear search (also called a sequential search) A linear search examines all values in a list until it finds a match or reaches the end A linear search locates a value in a list in O(n) steps A linear search is a very inefficient way to find a value in a large list

Binary Search A binary search is a technique for finding a particular value in a sorted linear array, by ruling out half of the data at each step A binary search finds the median, makes a comparison to determine whether the desired value comes before or after it, and then searches the remaining half in the same manner A binary search is an example of a divide and conquer algorithm (source – Wikipedia)

Binary Search Cont. An example of binary search in action is a simple guessing game in which a player has to guess a positive integer selected by another player between 1 and N, using only questions answered with yes or no. Supposing N is 16 and the number 11 is selected, the game might proceed as follows. Is the number greater than 8? (Yes) Is the number greater than 12? (No) Is the number greater than 10? (Yes) Is the number greater than 11? (No) Therefore, the number must be 11. At each step, we choose a number right in the middle of the range of possible values for the number. For example, once we know the number is greater than 8, but less than or equal to 12, we know to choose a number in the middle of the range [9, 12] (either 10 or 11 will do). Source - Wikipedia

Sorting Cont. (selection) // BINARY SEARCH public static int bSearch(int[ ] array, int value, int left, int right) { // Continue while left and right haven't // become equal or crossed over each other while (left < right) { // locate middle index between left and right int mid = (left + right) / 2; if (array[mid] < value) left = mid + 1; // in right half else if (array[mid] > value) right = mid; // in left half else return mid; // found it } return -1; // not found }

Reference: Big Java 2 nd Edition by Cay Horstmann Sorting: selection, insertion and bubble sort (section 19.1 in Big Java) Profiling the Selection Sort Algorithm (section 19.2 in Big Java) Analyzing the Performance of the Selection Sort Algorithm (section 19.3 in Big Java) Searching (section 19.6 in Big Java) Binary Search (section 19.7 in Big Java)