22
Examples using Arrays

Examples using Arrays

  • Upload
    sian

  • View
    20

  • Download
    1

Embed Size (px)

DESCRIPTION

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 - PowerPoint PPT Presentation

Citation preview

Page 1: Examples using Arrays

Examples using Arrays

Page 2: 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

Page 3: Examples using Arrays

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

Page 4: Examples using Arrays

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

Page 5: Examples using Arrays

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

Page 6: Examples using Arrays

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

Page 7: Examples using Arrays

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

Page 8: Examples 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

Page 9: Examples using Arrays

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 23 5 5 5

12 12 12 12 37 37 37 23

5 23 23 37

Page 10: Examples using Arrays

The algorithmAlgorithm 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

Page 11: Examples using Arrays

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)

Page 12: Examples using Arrays

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

Page 13: Examples using Arrays

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

Page 14: Examples using Arrays

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

Page 15: Examples using Arrays

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

Page 16: Examples using Arrays

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

Page 17: Examples using Arrays

Bubblesort program bubble_sort

... declarations and reading inputs

rt_end = N do if (rt_end < = 1) exit index = 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 = i endif enddo rt_end = index enddo print *, (Arr(i),i=1,N)

end program

Page 18: Examples using Arrays

Analysis

• Is the algorithm correct?

• How many number of operations?

• Can there be a better algorithm?

Page 19: Examples using Arrays

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

Page 20: Examples using Arrays

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

Page 21: Examples using Arrays

Program bin_search

....integer *, left, right left = 1right = Ndo If ((A(left)>x) .or. (A(right) < x)) then print *, "Not found" exit end if mid = (left + right)/2 If (A(mid)< x) then left = mid + 1 elseif (A(mid)>x) then right = mid else print *, x," is found at index ", mid exit end ifend do

Page 22: Examples using Arrays

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.