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.

Slides:



Advertisements
Similar presentations
Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs.
Advertisements

CSE Lecture 3 – Algorithms I
HST 952 Computing for Biomedical Scientists Lecture 9.
the fourth iteration of this loop is shown here
Simple Sorting Algorithms
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.
Chapter 3: Sorting and Searching Algorithms 3.2 Simple Sort: O(n 2 )
Algorithm Efficiency and Sorting
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Analysis of Algorithms CS 477/677
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Sorting 2 An array a is sorted (ascending order) if: for all i a[i]  a[j] Probably the most well-studied algorithmic problem in Computer Science There.
Searching and Sorting Arrays
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
Simple Sorting Algorithms. 2 Outline We are going to look at three simple sorting techniques: Bubble Sort, Selection Sort, and Insertion Sort We are going.
Advance Data Structure 1 College Of Mathematic & Computer Sciences 1 Computer Sciences Department م. م علي عبد الكريم حبيب.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
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.
SEARCHING UNIT II. Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances.
Additional Problems.
Searching. The process used to find the location of a target among a list of objects Searching an array finds the index of first element in an array containing.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
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.
CS 61B Data Structures and Programming Methodology July 28, 2008 David Sun.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
CSC 211 Data Structures Lecture 13
1 Today’s Material Iterative Sorting Algorithms –Sorting - Definitions –Bubble Sort –Selection Sort –Insertion Sort.
BUBBLE SORT. Introduction Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to.
Data Structure Introduction.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Sorting Many computer applications.
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.
CSCI 51 Introduction to Programming March 12, 2009.
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.
ALGORITHMS.
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.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
COMP108 Algorithmic Foundations Polynomial & Exponential Algorithms
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
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.
Dr. Sajib Datta CSE 1320 Arrays, Search and Sort.
 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.
SORTING Sorting is storage of data in some order, it can be in ascending or descending order. The term Sorting comes along-with the term Searching. There.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 8a. Sorting(1): Elementary Algorithms.
INTRO2CS Tirgul 8 1. Searching and Sorting  Tips for debugging  Binary search  Sorting algorithms:  Bogo sort  Bubble sort  Quick sort and maybe.
CSCE 210 Data Structures and Algorithms
Sorting With Priority Queue In-place Extra O(N) space
Growth of Functions & Algorithms
COMP108 Algorithmic Foundations Polynomial & Exponential Algorithms
Introduction to Search Algorithms
Recitation 13 Searching and Sorting.
Linear and Binary Search
Algorithm design and Analysis
Describing algorithms in pseudo code
Analysis of Bubble Sort and Loop Invariant
Sorting … and Insertion Sort.
Searching and Sorting 1-D Arrays
Search,Sort,Recursion.
Search,Sort,Recursion.
Algorithms.
Discrete Mathematics CS 2610
Module 8 – Searching & Sorting Algorithms
Presentation transcript:

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 and stored in an array

The Program Program sum_square implicit none integer:: N, Sum, Index, i ! N - the total number of items to be summed integer, dimension(100):: Arr Sum = 0 read *,N read *, (Arr(i), i= 1, N) do index = 1, N Sum = Sum + Arr(index) ** 2 end do print *, Sum end program

Another Example Searching an item in an array –Given an array of integers, check whether a given integer is in the array or not This is an abstraction of standard and important problem for searching an item from a large collection of data items Algorithm idea: –Examine each item in the array and compare with the given item –If there is a match return success, return failure otherwise This is called Linear Search

The program Program l_search implicit none integer:: N, Index, i, item ! N - the total number of items to be summed logical :: found ! logical variable that store the search result integer, dimension(100):: Arr read *,item read *,N read *, (Arr(i), i=1, N) found =.false. do index = 1, N if ( Arr(index) == item ) then found =.true. exit endif end do print *, found end program

Complexity of Linear Searching Total number of operations –depends on the input Worst case estimate –when the given item is not present in the array –constant number of operations per iteration –number of iterations is N –Total number of operations: (k*N) Can we do better? –Yes, if the array is sorted –(k*log N) algorithm

Sorting Sorting of data items is a very standard task in various applications –Rank students according to their marks –Order animals in a zoo in the order of their weights –Obtain the top 5% batsmen in one-day matches in a calendar year –Order the world cup footballers in the order of their goals Ascending and Descending Orders Sorting is a typical example using arrays

Specification of Sorting Input: A(1..N) is an array of integers Output: A(1..N) is the sorted (in ascending order) version of old array Sorted Version: The output A(1..N) is a permutation of old array. It is, further sorted in ascending order Examples: Input: Output:

How to do Sorting Simplest Strategy Choose the smallest number and place in the first position Choose the next smallest number and place in the second position and so on Illustration

The algorithm Algorithm Sort Input A(1:N) Output A(1:N) 1.read input values into A 2.i = 1 3.while (i < N) 3.1 find N >= j > i s.t. A(j) is the least element in A(i:N) 3.2 swap A(i) and A(j) 3.3 i = i+1 4.output A(1:N) This algorithm is called Selection Sort

Program Ssort implicit none integer:: N, i, j, min, temp ! N - total no. of items in array integer, dimension(100):: Arr print *, "input the size of the array" read *, N print *, "Input the array elements in the same line" read *, (Arr(i), I = 1, N) do i = 1, N min = i do j = i+1, N if (Arr(min) > Arr(j)) then min = j endif end do temp = Arr(i) Arr(i) = Arr(min) Arr(min) = temp end do print *, (Arr(i),I = 1, N)

Analysis Is the program Correct? –Find loop invariants for the do-loops How many number of operations? –Iterations count for the outer loop: N –Iteration count for the inner one: (N-1) for 1st, (N-2) for 2nd,... –Total operations (N-1) = N(N-1)/2 Can we do better? –Yes, More on this later

Bubble Sort Most sorting algorithms are based upon iterative swapping Selection sort, in each iteration, swaps A(i) with the least element in A(i+1),...,A(N) Bubble sort uses a simpler swap operation. –Swaps adjacent elements if they are in the wrong order Keep iterating such swaps until no adjacent elements are in the wrong order The array is sorted then

An abstract algorithm Here is a very high level description while there is a pair of adjacent elements in the wrong order swap the two elements end The details of algorithm is in systematically searching for the adjacent pair of elements in the wrong order Search from left to right

A simple version program b_sort... declarations and reading inputs do do i = 1, (N-1) if Arr(i) > Arr(i+1) then temp = Arr(i) Arr(i) = Arr(i+1) Arr(i+1) = temp swapped =.true. endif enddo if (.not. ( swapped)) exit enddo print *, (Arr(i),i=1,N) end program

An improvement This algorithm is correct (why?) The inner loop `sweeps' through the entire array in every iteration Observe that in the I iteration, the largest element goes rightmost, its right position In the II iteration, the second largest element reaches its destination and so on Every successive iteration needs to sweeps less and less to the right The same is the case if the array if already is sorted (in the right) Bubblesort makes use of this property

Bubblesort program bubble_sort... declarations and reading inputs rt_end = N do if (rt_end A(i+1)) then temp = Arr(i) Arr(i) = Arr(i+1) Arr(i+1) = temp index = i endif enddo rt_end = index enddo print *, (Arr(i),i=1,N) end program

Analysis Is the algorithm correct? How many number of operations? Can there be a better algorithm?

Sort before searching Recall the Linear Searching algorithm N comparisons are required One has to look at all the items Can we avoid looking at all items? It appears no but actually one need not, if the array is sorted In a sorted array, every section containing the item has: –left most item less than or equals and –right most item greater than or equals the searched item We give an algorithm exploiting this fact

Binary Search Algorithm Idea: –Obtain an initial section possibly containing the searched item –Keep reducing the size of the section until – the section contains just one or two elements What is the initial section? The entire array if the given item > = first item < = last item How to reduce a given section? –If the section contains k elements, break it into two (hence binary) sections, at most one of which will possibly contain the element

Program bin_search.... integer *, left, right left = 1 right = N do If ((A(left)>x).or. (A(right) x) then right = mid else print *, x," is found at index ", mid exit end if end do

Analysis of the algorithm Is the program correct? What is the loop invariant? Does the loop terminate? How many comparison? Log N in the worst case Can we do better? No.