Outline ArrayList Searching Sorting Copyright © 2012 Pearson Education, Inc.

Slides:



Advertisements
Similar presentations
CSE Lecture 3 – Algorithms I
Advertisements

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Chapter 11 Sorting and Searching. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Examine the linear search and.
Sorting Chapter 10.
Algorithm Efficiency and Sorting
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Sorting CS-212 Dick Steflik. Exchange Sorting Method : make n-1 passes across the data, on each pass compare adjacent items, swapping as necessary (n-1.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
1 Sorting/Searching and File I/O Sorting Searching Reading for this lecture: L&L
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.
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
Value Iteration 0: step 0. Insertion Sort Array index67 Iteration i. Repeatedly swap element i with.
1 Data Structures and Algorithms Sorting. 2  Sorting is the process of arranging a list of items into a particular order  There must be some value on.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Do Now Take out ch6 test answers – be ready to hand it in Pick a leader in each group of up to 3 students; Leader will retrieve a whiteboard, marker, and.
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.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Chapter 19 Searching, Sorting and Big O
1 Time Analysis Analyzing an algorithm = estimating the resources it requires. Time How long will it take to execute? Impossible to find exact value Depends.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 19: Searching and Sorting Algorithms.
Data Structures & Algorithms CHAPTER 4 Searching Ms. Manal Al-Asmari.
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.
 2005 Pearson Education, Inc. All rights reserved Searching and Sorting.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
Sorting Chapter 10. Chapter Objectives  To learn how to use the standard sorting methods in the Java API  To learn how to implement the following sorting.
CSC 211 Data Structures Lecture 13
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
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
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Searching & Sorting.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Searching Topics Sequential Search Binary Search.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Chapter 9: Sorting1 Sorting & Searching Ch. # 9. Chapter 9: Sorting2 Chapter Outline  What is sorting and complexity of sorting  Different types of.
 2006 Pearson Education, Inc. All rights reserved. 1 Searching and Sorting.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.
Chapter 16: Searching, Sorting, and the vector Type.
Copyright Prentice Hall Modified by Sana odeh, NYU
Searching and Sorting Searching algorithms with simple arrays
Chapter 9 Polymorphism.
Chapter 13: Searching and Sorting
Binary Search Back in the days when phone numbers weren’t stored in cell phones, you might have actually had to look them up in a phonebook. How did you.
The ArrayList Class An ArrayList object stores a list of objects, and is often processed using a loop The ArrayList class is part of the java.util package.
Data Structures and Algorithms
Outline Late Binding Polymorphism via Inheritance
Sorting and Searching -- Introduction
Arrays.
Presentation transcript:

Outline ArrayList Searching Sorting Copyright © 2012 Pearson Education, Inc.

The ArrayList Class An ArrayList object stores a list of objects An ArrayList object grows and shrinks as needed, adjusting its capacity as necessary The ArrayList class is part of the java.util package You can reference each object in the list using a numeric index just like the arrays Copyright © 2012 Pearson Education, Inc.

The ArrayList Class Index values of an ArrayList begin at 0 (not 1): 0"Bashful" 1"Sleepy" 2"Happy" 3"Dopey" 4"Doc" Elements can be inserted and removed The indices of the elements adjust accordingly Copyright © 2012 Pearson Education, Inc.

The ArrayList Class Copyright © 2012 Pearson Education, Inc. ArrayList cityList = new ArrayList (); //Add some cities in the list cityList.add("London"); // cityList now contains [London] cityList.add("Denver"); // cityList now contains [London, Denver] cityList.add("Paris"); // cityList now contains [London, Denver, Paris] cityList.add("Ankara"); // cityList now contains [London, Denver, Paris, Ankara]

See TestArrayList.java TestArrayList.java Copyright © 2012 Pearson Education, Inc.

ArrayList Methods ArrayList() Creates an empty list. add(o: Object): boolean Appends a new element o at the end of this list. add(index: int, o: Object): void Adds a new element o at the specified index in this list. clear(): void Removes all the elements from this list. Copyright © 2012 Pearson Education, Inc.

ArrayList Methods contains(o: Object): boolean Returns true if this list contains the element o. get(index: int): Object Returns the element from this list at the specified index. indexOf(o: Object): int Returns the index of the first matching element in this list. isEmpty(): boolean Returns true if this list contains no elements. Copyright © 2012 Pearson Education, Inc.

ArrayList Methods lastIndexOf(o: Object): int Returns the index of the last matching element in this list. remove(o: Object): boolean removes the element o from this list. size(): int returns the number of elements in this list. remove(index: int): boolean removes the element at the specified index. set(index: int, o: Object): Object sets the element at the specified index. Copyright © 2012 Pearson Education, Inc.

The ArrayList Class The type of object stored in the list is established when the ArrayList object is created: ArrayList names = new ArrayList (); ArrayList list = new ArrayList (); An ArrayList object cannot store primitive types, but wrapper classes are used instead. See Beatles.javaBeatles.java Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // Beatles.java Author: Lewis/Loftus // // Demonstrates the use of a ArrayList object. //******************************************************************** import java.util.ArrayList; public class Beatles { // // Stores and modifies a list of band members. // public static void main (String[] args) { ArrayList band = new ArrayList (); band.add ("Paul"); band.add ("Pete"); band.add ("John"); band.add ("George"); continue

Copyright © 2012 Pearson Education, Inc. continue System.out.println (band); int location = band.indexOf ("Pete"); band.remove (location); System.out.println (band); System.out.println ("At index 1: " + band.get(1)); band.add (2, "Ringo"); System.out.println ("Size of the band: " + band.size()); int index = 0; while (index < band.size()) { System.out.println (band.get(index)); index++; }

Copyright © 2012 Pearson Education, Inc. continue System.out.println (band); int location = band.indexOf ("Pete"); band.remove (location); System.out.println (band); System.out.println ("At index 1: " + band.get(1)); band.add (2, "Ringo"); System.out.println ("Size of the band: " + band.size()); int index = 0; while (index < band.size()) { System.out.println (band.get(index)); index++; } Output [Paul, Pete, John, George] [Paul, John, George] At index 1: John Size of the band: 4 Paul John Ringo George

Examples See ReverseFile.java ReverseFile.java See CountVowels.java CountVowels.java See CountWords.javaCountWords.java Copyright © 2012 Pearson Education, Inc.

Outline ArrayList Searching Sorting Copyright © 2012 Pearson Education, Inc.

Linear Search A linear search begins at one end of a list and examines each element in turn Eventually, either the item is found or the end of the list is encountered Copyright © 2012 Pearson Education, Inc.

Linear Search ArrayList implementation: LinearSearch2.java LinearSearch2.java Array implementation: LinearSearch.java LinearSearch.java Copyright © 2012 Pearson Education, Inc.

Binary Search Algorithm A binary search first examines the middle element of the list -- if it matches the target, the search is over If it doesn't, only one half of the remaining elements need be searched Since they are sorted, the target can only be in one half of the other Copyright © 2012 Pearson Education, Inc.

Binary Search The process continues by comparing the middle element of the remaining viable candidates Each comparison eliminates approximately half of the remaining data Eventually, the target is found or the data is exhausted Copyright © 2012 Pearson Education, Inc.

Binary Search Given a key and sorted array a[], find index i such that a[i] = key, or report that no such index exists.

Binary Search for lo hi

Binary Search for lo hi mid

Binary Search for lo hi

Binary Search for lo midhi

Binary Search for lohi

Binary Search for lohimid

Binary Search for lo hi

Binary Search for lo hi

Binary Search Array implementation: BinarySearch2.java BinarySearch2.java ArrayList implementation: BinarySearch.java BinarySearch.java Copyright © 2012 Pearson Education, Inc.

Problem size In many applications, it is easy to come up with a numeric value that specifies the problem size, which is generally denoted by the letter N. For most array applications, the problem size is simply the size of the array as indicated by the length constant. For most ArrayList applications, the problem size is simply the size of the ArrayList as indicated by the size() method. Copyright © 2012 Pearson Education, Inc.

Time complexity A measure of the amount of time required to execute an algorithm. Time complexity expresses the relationship between the size of the problem and the run time for the algorithm Time complexity analysis is independent of the programming language chosen to implement the algorithm and the speed of the computer on which the algorithm is executed Copyright © 2012 Pearson Education, Inc.

Time complexity Analysis is usually based on: –Number of arithmetic operations performed –Number of comparisons made –Number of times through a critical loop –Number of array elements accessed –… etc Copyright © 2012 Pearson Education, Inc.

Efficiency of Linear Search In the worst case—which occurs when the value you’re searching for comes at the end of the array or does not appear at all—linear search requires N steps. On average, it takes approximately half that. Copyright © 2012 Pearson Education, Inc. O (N)

Efficiency of Binary Search On each step in the process, the binary search algorithm rules out half of the remaining possibilities. In the worst case, the number of steps required is equal to the number of times you can divide the original size of the array in half until there is only one element remaining. In other words, what you need to find is the value of k that satisfies the following equation: 1 = N / 2 / 2 / 2 / 2... / 2 k times You can simplify this formula using basic mathematics: 1 = N / 2 k 2 k = N k = log 2 N Copyright © 2012 Pearson Education, Inc. O (log N)

Outline ArrayList Searching Sorting Copyright © 2012 Pearson Education, Inc.

Detailed Outline Sorting Selection Sort Insertion Sort Bubble Sort Copyright © 2012 Pearson Education, Inc.

Sorting Sorting data is one of the most important computing applications Sorting is the process of arranging a list of items in a particular order After sorting in ascending order: Copyright © 2012 Pearson Education, Inc.

Sorting There are many algorithms, which vary in efficiency, for sorting a list of items We will examine three specific algorithms, which are all quadratic in time: –Selection Sort –Insertion Sort –Bubble Sort Copyright © 2012 Pearson Education, Inc.

Outline Sorting Selection Sort Insertion Sort Bubble Sort Copyright © 2012 Pearson Education, Inc.

Selection Sort The strategy of Selection Sort: –select a value and put it in its final place in the list –repeat for all other values In more detail: –find the smallest value in the list –switch it with the value in the first position –find the next smallest value in the list –switch it with the value in the second position –repeat until all values are in their proper places Copyright © 2012 Pearson Education, Inc.

Selection Sort Copyright © 2012 Pearson Education, Inc.

Selection Sort Wikipedia

Selection Sort Implementations See SelectionSortDesc.java SelectionSortDesc.java See SelectionSortStr.java SelectionSortStr.java Sorting an array of String objects containing Turkish letters: ı ö ü ç ğ ş SelectionSortStrTR.javaSelectionSortStrTR.java Copyright © 2012 Pearson Education, Inc.

Outline Sorting Selection Sort Insertion Sort Bubble Sort Copyright © 2012 Pearson Education, Inc.

Insertion Sort Pick any item and insert it into its proper place in a sorted sublist –repeat until all items have been inserted In more detail: –consider the first item to be a sorted sublist (of one item) –insert the second item into the sorted sublist, shifting the first item as needed to make room to insert the new one –insert the third item into the sorted sublist (of two items), shifting items as necessary –repeat until all values are inserted into their proper positions Copyright © 2012 Pearson Education, Inc.

Insertion Sort Copyright © 2012 Pearson Education, Inc.

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration 3: step Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value Array index67 Iteration 4 711

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration 5: Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration 5: Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration Array index67

Insertion Sort Iteration i. Repeatedly swap element i with the one to its left if smaller. Property. After ith iteration, a[0] through a[i] contain first i+1 elements in ascending order Value 1714 Iteration 10 DONE Array index67

Insertion Sort Wikipedia

See InsertionSort.java InsertionSort.java Copyright © 2012 Pearson Education, Inc.

Outline Sorting Selection Sort Insertion Sort Bubble Sort Copyright © 2012 Pearson Education, Inc.

Bubble Sort It’s called bubble sort because –larger values gradually “bubble” their way upward to the end of the array like air bubbles rising in water. The technique is to make several passes through the array. –On each pass, pairs of adjacent elements are compared. –If the pair is in increasing order, we leave the values as they are. –If the pair is in decreasing order, we swap the values.

Pass 1 30, 50, 40, 80, 70, 10, 90, 60 30, 40, 50, 80, 70, 10, 90, 60 30, 40, 50, 70, 80, 10, 90, 60 30, 40, 50, 70, 10, 80, 90, 60 30, 40, 50, 70, 10, 80, 60, 90 Copyright © 2012 Pearson Education, Inc.

Pass 2 30, 40, 50, 70, 10, 80, 60, 90 30, 40, 50, 10, 70, 80, 60, 90 30, 40, 50, 10, 70, 60, 80, 90 Continue.. Copyright © 2012 Pearson Education, Inc.

Bubble Sort Wikipedia

See BubbleSortAl.java BubbleSortAl.java See BubbleSortStr.java BubbleSortStr.java Copyright © 2012 Pearson Education, Inc.

Example Count the words in a file and sort them See CountWords2.java and CountWordsJava.pdf CountWords2.java CountWordsJava.pdf Copyright © 2012 Pearson Education, Inc.

Advice! Try to implement sorting algorithms by yourself Copyright © 2012 Pearson Education, Inc.

Comparing Sorts The Selection and Insertion sort algorithms are similar in efficiency They both have outer loops that scan all elements, and inner loops that compare the value of the outer loop with almost all values in the list Approximately N 2 number of comparisons are made to sort a list of size n We therefore say that these sorts are of order N 2 There are other sorting algorithms that are more efficient: order N log 2 N Copyright © 2012 Pearson Education, Inc.

Advantages / Disadvantages of Bubble Sort, Insertion, Selection Sort Advantage: they are easy to program. Disadvantage: it is very slow. Much work in computer science has been geared towards creating more efficient sorting algorithms. For example: –Merge Sort –Heapsort –Quick Sort

Comparison of sorting algorithms Graph from Alan Jepson University of Torontoc.