Chapter 10 - Notes Applications of Arrays

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

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

Solutions to Chapter 8

C/C++ Programming Lecture 18 Name:

Arrays. Week 4. Assylbek Jumagaliyev

LECTURE 17. Array Searching and Sorting

Lecture 6 Sorting and Searching

Lab Instructor : Jean Lai

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 6: One Dimensional Array

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

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

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

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

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

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

! 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 in Java Bubble Sort

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

C++ PROGRAMMING SKILLS Part 4: Arrays

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

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

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

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

Ch 5-2. Arrays Part 2

Search,Sort,Recursion

Chapter 5: Searching & Sorting

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

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

Search Algorithms. Linear Search Binary Search

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

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

Chapter 17 - Notes Recursion

SORTING AND SEARCHING

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

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

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

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

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

Why Is Repetition Needed?

Searching. 11. Searching

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

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

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

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

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

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

Algorithm Analysis. Performance Factors

Recursion. ! When the initial copy finishes executing, it returns to the part of the program that made the initial call to the function.

UNIT 7. SEARCH, SORT AND MERGE

Linked List using a Sentinel

CS 2412 Data Structures. Chapter 10 Sorting and Searching

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Data Structures and Algorithms for Engineers

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

Due Date: See Blackboard

ECE 2574: Data Structures and Algorithms - Basic Sorting Algorithms. C. L. Wyatt

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

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

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

LECTURE 08 SEARCHING AND SORTING ARRAYS

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

Increment and the While. Class 15

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

1 #include <iostream> 2 #include <stdlib.h> //srand, rand 3 #include <time.h>//clock_t, clock, CLOCKS_PER_SEC 4 using namespace std; 5 6 //

Unit 10: Sorting/Searching/Recursion

CmpSci 187: Programming with Data Structures Spring 2015

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

1 #include <iostream> 2 #include <string> 3 #include <cstring> 4 #include <stdlib.h> //srand, rand 5 #include <time.h>//clock_t, clock,

Introduction to Arrays

Introduction to Programming I COS1511 School of Computing Revision Notes

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

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

1 #include <iostream> 2 #include <stdlib.h> //srand, rand 3 #include <time.h>//clock_t, clock, CLOCKS_PER_SEC 4 using namespace std; 5 6 //

Chapter Four: Loops II

CS 106 Introduction to Computer Science I

Programming Language. Functions. Eng. Anis Nazer First Semester

Due Date: See Blackboard

Data Types. Operators, Assignment, Output and Return Statements

Chapter 10 Sorting and Searching Algorithms

Quadratic Sorting Algorithms

Chapter 8 Algorithms 1

CP222 Computer Science II. Searching and Sorting

Searching and Sorting

do { statements } while (condition);

Spring 2010 Java Programming

Summary of basic C++-commands

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Sorting and Searching Algorithms

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

Sorting and Searching

Objectives To estimate algorithm efficiency using the Big O notation ( 18.2).

Chapter 13. If the list is in increasing order; no interchanges are required.

Computer Science 4U Unit 1. Programming Concepts and Skills Algorithms

Due Date: See Blackboard

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

Lab 14 SERACHI G Dr. John P. Abraham

9/10/12. Outline. Part 5. Computational Complexity (2) Examples. (revisit) Properties of Growth-rate functions(1/3)

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

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

Transcription:

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 one-dimensional array. 2. The size of a list can increase and decrease, therefore, the list should be stored in an array large enough to hold the maximum size of the list. 3. Basic operations performed on a list are: a. Search the list for a given item. b. Sort the list. c. Insert an item into the list. d. Delete an item from the list. C. Searching 1. The most common operation on a list. 2. To search the list, you need three pieces of information: a. The list or the array containing the list. b. The length of the list. ( Not the length of the array. ) c. The item for which you are searching. 3. After the search is completed, you should either: a. Report "success" and the position where the item was found b. or Report "failure". -1-

4. Sequential Search or Linear Search Function a. A value returning function with the following parameters: i. The array containing the list. ii. The length of the list, listlength. (listlength <= arraysize) iii. The item for which you are searching, searchitem. b. The function s the searchitem with the elements of the list in the array starting at position zero (0) and continues until it has either found the item or come to the end of the list. c. Two conditions exist for a loop to search the list: i. Exit loop when the item is found... ii. or exit the loop when all elements of the list have been searched without success. d. Examples of Search Functions: int seqsearch ( const int list[ ], int listlength, int searchitem ) int loc ; bool found = false ; for ( loc = 0 ; loc < listlength ; loc++ ) if ( list[loc] = = searchitem ) found = true ; break ; if ( found ) return loc ; else return -1 ; OR - - - it can be written as follows: int seqsearch ( const int list[ ], int listlength, int searchitem ) int loc ; for ( loc = 0 ; loc < listlength ; loc++ ) if ( list[loc] = = searchitem ) return loc ; return -1 ; -2-

e. Sample Program using SeqSearch function: #include <iostream> #include <cstdlib> #include <time.h> using namespace std; const int asize = 00 ; int seqsearch ( const int list[ ], int listlength, int searchitem ) int loc ; for ( loc = 0 ; loc < listlength ; loc++ ) if ( list[loc] = = searchitem ) return loc ; return -1 ; int main ( ) int intlist [ asize ] ; int i, listsize, look4num, result ; srand( (unsigned) time( NULL ) ); cout << "Please enter an integer for the size of list you want: " ; cin >> listsize ; for ( i = 0 ; i < listsize ; i++ ) intlist [ i ] = rand( ) % 0 + 1 ; cout << endl << "Please enter an integer between 1 and 0 to search: "; cin >> look4num ; cout << endl; result = seqsearch ( intlist, listsize, look4num ) ; if ( result!= -1 ) cout << "Number " << look4num << " can be found at position " << result << endl << endl ; else cout << "Sorry, number " << look4num << " is not in the list." << endl << endl; system("pause") ; return 0 ; -3-

f. Inefficiency of Sequential Search i. On average, the time it will take to search a list for an element is half the size of the list. ii. iii. If the list is extremely large, this can cost valuable CPU time. Remember, the above sequential search is on an unsorted list.. Sorting a List : Bubble Sort a. Suppose we would like to sort a list of n integers so that they reside in the list/array in ascending order ( smallest to largest ). b. Given the following list :,,,,... We can demonstrate how the Bubble Sort works. list [0] [1] [2] [3] [4] & swap & swap & swap How the Elements of LIST get rearranged in the First Iteration -4-

& swap & swap How the Elements of LIST get rearranged in the Second Iteration & swap & swap How the Elements of LIST get rearranged in the Third Iteration How the Elements of LIST get rearranged in the Last Iteration --

c. The above illustrations show how the list is logically sorted. The following is an example of a program that uses a function that implements the Bubble Sort in code. #include <iostream> using namespace std; void bubblesort ( int list[ ], int length ) int temp, i, k ; for ( i = 0 ; i < length - 1 ; i++ ) for ( k = 0 ; k < length - 1 - i ; k++ ) if ( list[k] > list[k+1] ) temp = list[k] ; list[k] = list[k+1] ; list[k+1] = temp ; int main ( ) int list [ ] = 2,, 34, 2, 3, 4, 89,,, 1 ; int i ; bubblesort ( list, ) ; cout << "After sorting, the list elements are: " << endl ; for ( i = 0 ; i < ; i++ ) cout << list [ i ] << " " ; cout << endl ; system("pause") ; return 0 ; --

. Sorting a List : Selection Sort a. In the Selection Sort, we rearrange the list by selecting an element in the list and moving it to its proper position. b. In the first iteration, we locate the smallest item in the list and exchange it with the first position. In the second iteration, we locate the smallest item in the list, starting at the second position, and exchange it with the second position. And so on... c. Example [0] [1] [2] [3] [4] [] [] [] [8] [9] list 1 30 24 2 2 4 0 unsorted list swap [0] [1] [2] [3] [4] [] [] [] [8] [9] list 1 30 24 2 2 4 0 unsorted list swap [0] [1] [2] [3] [4] [] [] [] [8] [9] list 30 24 2 2 4 1 0 sorted unsorted list swap [0] [1] [2] [3] [4] [] [] [] [8] [9] list 24 30 2 2 4 1 0 sorted unsorted list --

swap [0] [1] [2] [3] [4] [] [] [] [8] [9] list 1 30 2 2 4 24 0 sorted unsorted list!!! swap [0] [1] [2] [3] [4] [] [] [] [8] [9] list 1 24 2 30 4 0 2 sorted unsorted list d. Example of a function that implements the Selection Sort. void selectionsort ( int list[ ], int length ) int index, smallestindex, minindex, temp ; for ( index = 0; index < length - 1 ; index++ ) smallestindex = index ; for ( minindex = index + 1 ; minindex < length ; minindex++ ) if ( list [ minindex ] < list [ smallestindex ] ) smallestindex = minindex ; temp = list [ smallestindex ] ; list [ smallestindex ] = list [ index ] ; list [ index ] = temp ; -8-

e. The following is an example of a program using the Selection Sort. # include < iostream > using namespace std; void selectionsort( int list[ ], int length ) int index, possmallest, inrindex, temp ; for ( index = 0 ; index < length - 1; index++ ) possmallest = index ; for ( inrindex = index + 1 ; inrindex < length ; inrindex++ ) if ( list[ inrindex ] < list [ possmallest ] ) possmallest = inrindex ; ; temp = list [ possmallest ] ; list [ possmallest ] = list [ index ] ; list [ index ] = temp ; int main ( ) int list [ ] = 2,, 34, 2, 3, 4, 89,,, 1 ; int i ; selectionsort ( list, ) ; cout << "After sorting, the list elements are: " << endl << endl ; for ( i = 0 ; i < length ; i++ ) cout << list [ i ] << " " : cout << endl << endl ; system("pause") ; return 0 ; -9-

. Sorting a List : Insertion Sort a. The insertion sort algorithm sorts the list by moving each element to its proper place. b. It does this by splitting the list up into two sublists; the sorted part and the unsorted part. As it cycles through the unsorted part of the sublist, it inserts the unsorted value into the proper position in the sorted part of the list. As the sorted part of the list grows, the unsorted part of the list gets smaller, until all values have been inserted in the sorted part of the list. c. Example [0] [1] [2] [3] [4] [] [] [] [8] [9] list 1 30 24 21 2 4 0 unsorted list d. After the first four values have been sorted. [0] [1] [2] [3] [4] [] [] [] [8] [9] list 1 24 30 21 2 4 0 sorted unsorted e. Now we can see that the next item in the unsorted part of the list is the value 21 at position list[4], which should be inserted at position list[2] in the sorted part of the list. [0] [1] [2] [3] [4] [] [] [] [8] [9] list 1 24 30 21 2 4 0 sorted unsorted --

f. To move the value in list[4] into the space list[2], we must first copy the value in list[4] into a variable we will call 'temp'. [0] [1] [2] [3] [4] [] [] [] [8] [9] list 1 24 30 21 2 4 0 sorted unsorted temp copy 21 g. Next, we copy the value in list[3] into the space list[4], and then we copy the value in list [2] into the space list[3]. [0] [1] [2] [3] [4] [] [] [] [8] [9] list 1 24 30 21 2 4 0 sorted unsorted temp 21 copy copy h. The list should now look like the following: [0] [1] [2] [3] [4] [] [] [] [8] [9] list 1 24 24 30 2 4 0 sorted unsorted temp 21-11-

i. The next obvious step is to copy the value in our 'temp' variable into the space list[2] and increase our sorted list by one while decreasing our unsorted list by one. [0] [1] [2] [3] [4] [] [] [] [8] [9] list 1 21 24 30 2 4 0 sorted unsorted temp 21 j. Now you can see that we repeat these steps until every value in the unsorted list is inserted into the sorted side. k. The following code is an example of what a function would look like to implement the insertion sort: void insertionsort( int list[ ], int listlength ) int firstoutoforder, location; int temp; for ( firstoutoforder = 1 ; firstoutoforder < listlength; firstoutoforder++ ) if (list[firstoutoforder] < list[firstoutoforder - 1]) temp = list[firstoutoforder]; location = firstoutoforder; do list[location] = list[location - 1]; location- - ; while ( location > 0 && list[location - 1] > temp); ; list[location] = temp; -12-

8. Sequential Search on an Ordered List a. For a sequential search of an ordered ( sorted ) list, you search until you arrive at an item that is greater than or equal to what you are searching for, or the list has no more elements to search. b. A Function Implementing a Sequential Ordered Search: int seqorderedsearch ( const int list [ ], int listlength, int searchitem ) int loc ; bool found = false ; for ( loc = 0 ; loc < listlength ; loc++ ) if ( list [ loc ] >= searchitem ) found = true ; break ; if ( found ) if ( list [ loc ] == searchitem ) return loc ; else return -1 ; else return -1 ; 9. Binary Search a. An efficient search on an already sorted list is the Binary Search. It uses the divide and conquer approach. b. First, the search item is d with the value in the middle position of the list. If the value in the middle is greater than the search item, the first half of the list is searched, else if the value in the middle is less than the search item, then the second half of the list is searched. -13-

c. This method is again repeated. The middle position value of the half that is to be searched is d with the search item. And the process is repeated. d. Example: Searching for the number [0] [1] [2] [3] [4] [] [] [] [8] [9] [] [11] list 4 8 2 34 39 4 48 89 9 search list mid [0] [1] [2] [3] [4] [] [] [] [8] [9] [] [11] list 4 8 2 34 39 4 48 89 9 search list mid [0] [1] [2] [3] [4] [] [] [] [8] [9] [] [11] list 4 8 2 34 39 4 48 89 9 search list [0] [1] [2] [3] [4] [] [] [] [8] [9] [] [11] list 4 8 2 34 39 4 48 89 9 mid search list found [0] [1] [2] [3] [4] [] [] [] [8] [9] [] [11] list 4 8 2 34 39 4 48 89 9-14-

e. The Binary Search Function int binarysearch ( const int list [ ], int listlength, int searchitem ) int first = 0 ; int last = listlength - 1 ; int mid ; bool found = false ; while ( first <= last &&! found ) mid = ( first + last ) / 2 ; if ( list [ mid ] = = searchitem ) found = true ; else if ( list [ mid ] > searchitem ) last = mid - 1 ; else first = mid + 1 ; if ( found ) return mid ; else return -1 ;. Performance of Binary Search a. Suppose you sort a list of 00 elements with the Binary Search. b. Because 00 24 = 2, a while loop will have at most 11 iterations to find the searched item. c. Because every iteration of the while loop makes at most two comparisons, the Binary Search will make at most 22 comparisons to determine if the search item is in the list. d. For a list of 00, A Binary Search takes 22 comparisons while a Sequential Search averages 00 comparisons. e. Bottom Line: The larger the size of the list, the more efficient a Binary Search is over a Sequential Search. -1-