220 likes | 310 Views
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
E N D
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_searchimplicit noneinteger:: N, Index, i, item! N - the total number of items to be summedlogical :: found! logical variable that store the search resultinteger, dimension(100):: Arrread *,itemread *,Nread *, (Arr(i), i=1, N)found = .false.do index = 1, Nif ( Arr(index) == item ) then found = .true.exitendifend doprint *, foundend 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 andDescendingOrders • 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:9 3 4 8 10 34 2 7 11 10 Output:2 3 4 7 8 9 10 10 11 34
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 37373723 5232337
The algorithm Algorithm Sort Input A(1:N) Output A(1:N) • read input values into A • i = 1 • 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 • output A(1:N) • This algorithm is called Selection Sort
Program Ssort implicit noneinteger:: N, i, j, min, temp ! N - total no. of items in arrayinteger, dimension(100):: Arr print *, "input the size of the array"read *, Nprint *, "Input the array elements in the same line"read *, (Arr(i), I = 1, N)do i = 1, N min = ido j = i+1, Nif (Arr(min) > Arr(j)) then min = jendifend do temp = Arr(i) Arr(i) = Arr(min) Arr(min) = tempend 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 1 + 2 + 3 + ... (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 inputsdodo 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 enddoif (.not. ( swapped)) exitenddo 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 inputsrt_end = Ndo if (rt_end < = 1) exitindex = 0 do i = 1, (rt_end-1) if (A(i) > A(i+1)) then temp = Arr(i) Arr(i) = Arr(i+1) Arr(i+1) = temp index = iendifenddort_end = index enddoprint *, (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 = 1right = NdoIf ((A(left)>x) .or. (A(right) < x)) then print *, "Not found"exitend ifmid = (left + right)/2If (A(mid)< x) then left = mid + 1elseif (A(mid)>x) then right = midelse print *, x," is found at index ", midexitend ifend 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.