Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Examples using Arrays

2 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

3 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

4 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

5 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

6 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

7 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

8 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: 9 3 4 8 10 34 2 7 11 10 Output: 2 3 4 7 8 9 10 10 11 34

9 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 23555 12121212 373737 23 52323 37

10 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

11 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)

12 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 1 + 2 + 3 +... (N-1) = N(N-1)/2 Can we do better? –Yes, More on this later

13 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

14 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

15 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

16 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

17 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

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

19 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

20 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

21 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

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


Download ppt "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."

Similar presentations


Ads by Google