Presentation is loading. Please wait.

Presentation is loading. Please wait.

Algorithms & Arrays.

Similar presentations


Presentation on theme: "Algorithms & Arrays."— Presentation transcript:

1 Algorithms & Arrays

2 Informal definition of an algorithm
used in a computer

3 Finding the largest integer
among five integers

4 Defining actions in FindLargest algorithm

5 FindLargest refined

6 Generalization of FindLargest

7 Characteristics of algorithm
Precision – the steps are precisely stated(defined). Uniqueness – results of each step are uniquely defined and only depend on the input and the result of the preceding steps. Finiteness – the algorithm stops after a finite number of instructions are executed. Input – the algorithm receives input. Output – the algorithm produces output. Generality – the algorithm applies to a set of inputs.

8 Three constructs

9 Write an algorithm to find the largest of 1000 numbers.
Solution See Algorithm on the next slide.

10 Algorithm : Find largest of 1000 numbers FindLargest
Input: 1000 positive integers Set Largest to 0 Set Counter to 0 while (Counter less than 1000) if (the integer is greater than Largest) then Set Largest to the value of the integer End if Increment Counter End while Return Largest End

11 ARRAYS An array is a collection of elements of the same type
that are referenced by a common name. Compared to the basic data type (int, float & char) it is an aggregate or derived data type. All the elements of an array occupy a set of contiguous memory locations.

12 int studMark0, studMark1, studMark2, ..., studMark999;
Why ARRAYS? "We have a list of 1000 students' marks of an integer type. If using the basic data type (int), we will declare something like the following…" int  studMark0, studMark1, studMark2, ..., studMark999; Can you imagine how long we have to write the declaration part by using normal variable declaration? int main() { int studMark1, studMark2, studMark3,…………studMark1000; ………… return 0; }

13 ARRAYS By using an array, we just declare like this,
int  studMark[1000]; This will reserve 1000 contiguous memory locations for storing the students’ marks. Graphically, this can be depicted as in the following figure.

14 Arrays in Memory Assuming integer takes 2 bytes of storage

15 Arrays One Dimensional Array: Declaration
A single or one dimensional array declaration has the following form, array_data_type  array_name[array_size]; Here, array_data_type define the base type of the array, which is the type of each element in the array. array_name is any valid C / C++ identifier name that obeys the same rule for the identifier naming. array_size defines how many elements the array will hold.

16 Arrays For example, to declare an array of 30 characters, that construct a people name, we could declare, char   cName[30]; Which can be depicted as follows, In this statement, the array character can store up to 30 characters with the first character occupying location cName[0] and the last character occupying cName[29].  Note that the index runs from 0 to 29.  In C, an index always starts from 0 and ends with array's (size-1).

17 Arrays An array may be initialized at the time of declaration.
Array Initialization An array may be initialized at the time of declaration. Initialization of an array may take the following form, type  array_name[size] = {a_list_of_value}; For example: int    idNum[7] = {1, 2, 3, 4, 5, 6, 7}; float  fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1}; The first line declares an integer array idNum and it immediately assigns the values 1, 2, 3, ..., 7 to idNum[0], idNum[1], idNum[2],..., idNum[6] respectively. The second line assigns the values 5.6 to fFloatNum[0], 5.7  to  fFloatNum[1], and so on.

18 1-D Array Homogeneous data:
a) Elements are represented through indexes. b) Elements are saved in sequential in memory locations. Number of elements, N –> length or size of an array. If: UB : upper bound ( the largest index) LB : lower bound (the smallest index) Then: N = UB – LB + 1 Length = N = UB when LB = 1 Department of CSE

19 Address Calculation in 1-D Array
The process to determine the address in a memory: a) First address –> base address. b) Relative address to base address through index function. Example: char X[100]; Let char uses 1 location storage. If the base address is 1200 then the next element is in 1201. Index Function is written as: Loc (X[i]) = Loc(X[0]) + i , i is subscript and LB = 0 X[0] X[1] X[2]

20 Address Calculation in 1-D Array(..contd)
In general, index function: Loc (X[i]) = Loc(X[LB]) + w*(i-LB); where w is length of memory location required. For real number: 4 byte, integer: 4 byte and character: 1 byte. Example: If LB = 5, Loc(X[LB]) = 1200, and w = 4, find Loc(X[8]) ? Loc(X[8])= Loc(X[5]) + 4*(8 – 5) = 1212

21 2-D Array Imagine now we want to keep 10 test scores for 30 students.
How would we represent this in a program with what we’ve learned? Answer: You would need either element arrays or element arrays. What we have been working with so far are considered one dimensional arrays, because they only extend along one dimension (one set of data). “C” allows for higher dimensional arrays, for example, two dimensional arrays. Two dimensional arrays can be though of having a table of rows and columns in memory. So, a better solution to the above question is what? Answer: Have a 30 x 10 or a 10 x 30 two dimensional array! Department of CSE

22 Storage Order Row-major order: the array is stored as a sequence of arrays consisting of rows (0,0) (0,1) (0,2) 1 2 3 5 4 6

23 Storage Order Column-major order: The array is stored as a sequence of arrays consisting of columns instead of rows (0,0) (1,0) (0,1) 1 2 3 5 4 6

24 Address Calculation in 2-D Array
When lower bound is not given. The computer keeps track of Base (BA),:-  the address of the first element A[0][0] of A[M][N],  and computes address i.e. Loc (A[I][J]) of A[M][N] using the formula Loc(A[I][J])=Base (BA)+W[M*J + I] [Column Major] Loc(A[I][J])=Base (BA)+W[N*I + J] {Row- Major} W denotes the size, i.e; number of bytes per data element of the array A, M is total numbers of rows, and N is total number of columns in the array. Department of CSE

25 Address Calculation in 2-D Array(..contd)
When lower bound is given Loc(A[I][J])=Base (BA)+W[M*(J-LBC) + (I-LBR)] [Column Major] Loc(A[I][J])=Base (BA)+W[N*(I-LBR) + (J-LBC)] {Row- Major} In case of ‘C’ LBR=0 (Lower Bound Row) LBC=0 (Lower Bound Column) Department of CSE

26 Example Suppose element of array A[4][5] occupies 4 bytes, and the address of the 1st element is 49.  Find the address of the element A(4,3) when the storage is row major. = BA + [N * (I - LBR) + (J - LBC)] * W  = 49 + [5 * (4 – 0) + (3 - 0)] * 4  = 49 + [23] * 4  =  = 141 Department of CSE

27 Special Matrices A square matrix has the same number of rows and columns. Some special forms of square matrices are Diagonal: M(i,j) = 0 for i ≠ j Tridiagonal: M(i,j) = 0 for |i-j| < =1 Lower triangular: M(i,j) = 0 for i < j Upper triangular: M(i,j) = 0 for i > j Symmetric M(i,j) = M(j,i) for all i and j

28 Fig. 1 Special Matrices

29 Special Matrices Why are we interested in these “special” matrices?
We can provide more efficient implementations for specific special matrices. Rather than having a space complexity of O(n2), we can find an implementation that is O(n). We need to be clever about the “store” and “retrieve” operations to reduce time.

30 Distance Matrix

31 Diagonal Matrix Naive way to represent n x n diagonal matrix
T d[n][n] d[i-1][j-1] for D(i,j) requires n2 x sizeof(T) bytes of memory Better way T d[n] d[i-1] for D(i,j) where i = j 0 for D(i,j) where i ≠ j requires n x sizeof(T) bytes of memory

32 Tridiagonal Matrix Nonzero elements lie on one of three diagonals:
main diagonal: i = j diagonal below main diagonal: i = j+1 diagonal above main diagonal: i = j-1 3n-2 elements on these three diagonals: T t[3n-2] Mappings of Figure 1(b) by row [2,1,3,1,3,5,2,7,9,0] by column [2,3,1,1,5,3,2,9,7,0] by diagonal [3,5,9,2,1,2,0,1,3,7]

33 Triangular Matrix Nonzero elements lie in the region marked “nonzero” in the figure below 1+2+…+n = Σ(i=1..n) = n(n+1)/2 elements in the nonzero region

34 Triangular Matrix Both triangular matrices may be represented using 1-D array  T t[n(n+1)/2] Mappings by row?  [2,5,1,0,3,1,4,2,7,0] by column?  [2,5,0,4,1,3,2,1,7,0]

35 Symmetric Matrix An n x n matrix can be represented using 1-D array of size n(n+1)/2 by storing either the lower or upper triangle of the matrix Use one of the methods for a triangular matrix The elements that are not explicitly stored may be computed from those that are stored How do we compute this?

36 Sparse Matrix A matrix is sparse if many of its elements are zero
A matrix that is not sparse is dense Two possible representations array linked list

37 Array Representation of Sparse Matrix
The nonzero entries may be mapped into a 1D array in row-major order To reconstruct the matrix structure, need to record the row and column each nonzero comes from

38 Input and print array in C
int main() {     int i, arr[50], num;     printf("\nEnter no of elements :");    scanf("%d", &num);     //Reading values into Array    printf("\nEnter the values :");    for (i = 0; i < num; i++)        scanf("%d", &arr[i]);    }  //Printing of all elements of array    for (i = 0; i < num; i++)        printf("\narr[%d] = %d", i, arr[i]);    }     return (0); }

39 Input and print array in C++
//For loop to fill & print a 10-int array int main ( ) { int index, ar[10]; // array for 10 integers // Read in 10 elements. cout << "Enter 10 integers: "; for(index = 0; index < 10; index ++) cin >> ar[index]; cout << endl; cout << "The integers are "; cout << ar[index] << " "; return 0; }

40 Basic Operations Following are the basic operations supported by an array. Traverse − print all the array elements one by one. Insertion − Adds an element at the given index. Deletion − Deletes an element at the given index. Search − Searches an element using the given index or by the value.

41 Traversal Description: Here A  is a linear array with lower bound  LB  and upper bound  UB. This algorithm traverses array A and applies the operation PROCESS to each element of the array. 1.  Repeat For I = LB to UB 2.    Apply PROCESS to A[I]        [End of For Loop] 3.  Exit

42 Deletion algorithm DELETE (LA, N, K, ITEM)  Here LA is a Linear Array with N elements and K is the positive integer such that K<=N. This algorithm deletes the Kth element from LA. 1. Set ITEM: = LA [k]. 2. Repeat for J = K to N – 1. [Move J + 1st element upward] Set LA [J]: = LA [J +1]. [End of loop] 3. [Reset the number N of elements in LA] Set N: = N-1 4. EXIT

43 Insertion algorithm INSERT (LA, N, K, ITEM)
1. [Initialize counter] Set J: = N. 2. Repeat Steps 3 and 4 while j >= k; 3. [Move jth element downward.] Set LA [J + 1]: =LA [J]. 4. [Decrease counter] Set J: = J-1 [End of step 2 loop] 5. [Insert element] Set LA [K]:=ITEM. 6. [Reset N] Set N:=N+1 7. EXIT.

44 Linear Search Linear Search ( Array A, Value x) Step 1: Set i to 1 Step 2: if i > n then go to step 7 Step 3: if A[i] = x then go to step 6 Step 4: Set i to i + 1 Step 5: Go to Step 2 Step 6: Print Element x Found at index i and go to step 8 Step 7: Print element not found Step 8: Exit

45 Binary Search

46 Bubble Sort BUBBLE-SORT(a) Time complexity is O(n2). for i = 0 to n-1
for j =0 to n-2 if key[j] > key[j+1] then swap if no elements swapped in this pass through array, done otherwise, continue Time complexity is O(n2). for j =0 to n-2 if key[j] > key[j+1] then swap

47 Example

48 Strings Characters Strings Building blocks of programs
Every program is a sequence of meaningfully grouped characters Strings Series of characters treated as a single unit Can include letters, digits and special characters (*, /, $) String literal (string constant) - written in double quotes "Hello" Strings are arrays of characters

49 Contd.. String declarations Inputting strings
Declare as a character array or a variable of type char * char color[] = "blue"; char *colorPtr = "blue"; Remember that strings represented as character arrays end with '\0' color has 5 elements Inputting strings Use scanf scanf("%s", word); Copies input into word[] Do not need & (because a string is a pointer) Remember to leave room in the array for '\0'

50 String Conversion Functions
In <stdlib.h> (general utilities library) Convert strings of digits to integer and floating-point values

51 Standard Input/output Library Functions
Functions in <stdio.h> Used to manipulate character and string data

52 Example #include <stdio.h> int main() { char str[20]; sprintf(str, “Data Structure"); puts(str); return(0); }

53 Example #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int day, year; char weekday[20], month[20], dtm[100]; strcpy( dtm, "Friday Jan " ); sscanf( dtm, "%s %s %d %d", weekday, month, &day, &year ); printf("%s %d, %d = %s\n", month, day, year, weekday ); }

54 String Manipulation Functions
String handling library has functions to Manipulate string data Search strings Tokenize strings Determine string length

55 #include <stdio.h>
#include <string.h> int main() { char s1[ 20 ] = "Happy "; char s2[] = "New Year "; char s3[ 40 ] = ""; printf( "s1 = %s\ns2 = %s\n", s1, s2 ); printf( "strcat( s1, s2 ) = %s\n", strcat( s1, s2 ) ); printf( "strncat( s3, s1, 6 ) = %s\n", strncat( s3, s1, 6 ) ); printf( "strcat( s3, s1 ) = %s\n", strcat( s3, s1 ) ); return 0; } s1 = Happy s2 = New Year strcat( s1, s2 ) = Happy New Year strncat( s3, s1, 6 ) = Happy strcat( s3, s1 ) = Happy Happy New Year

56 Comparison Functions Comparing strings
Computer compares numeric ASCII codes of characters in string int strcmp( const char *s1, const char *s2 ); Compares string s1 to s2 Returns a negative number if s1 < s2, zero if s1 == s2 or a positive number if s1 > s2 int strncmp( const char *s1, const char *s2, size_t n ); Compares up to n characters of string s1 to s2 Returns values as above

57 Example #include<stdio.h> #include<string.h> int main() {
char str1[]="hello"; char str2[]="NESTLE MAGGI"; int i; i=strcmp(str1,str2); printf("%d",i); return 0; }


Download ppt "Algorithms & Arrays."

Similar presentations


Ads by Google