Arrays Department of Computer Science. C provides a derived data type known as ARRAYS that is used when large amounts of data has to be processed. “ an.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 7: Arrays In this chapter, you will learn about
One Dimensional Arrays
CSE Lecture 3 – Algorithms I
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 9: Searching, Sorting, and Algorithm Analysis
11.5 SORTING ARRAY Sorting is the process of transforming a list into an equivalent list, in which the elements are arranged in ascending or descending.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Chapter 8 Search and Sort Asserting Java ©Rick Mercer.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Introduction to Programming with C++ Fourth Edition
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Searching and Sorting Arrays
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic concepts and uses of arrays ❏ To be able to define C.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 3: The Fundamentals: Algorithms, the Integers, and Matrices
C How to Program, 6/e Summary © by Pearson Education, Inc. All Rights Reserved.
Array Processing Simple Program Design Third Edition A Step-by-Step Approach 7.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
CHAPTER 09 Compiled by: Dr. Mohammad Omar Alhawarat Sorting & Searching.
Chapter 8 Arrays and Strings
Analysis of Algorithms
Chapter 7 One-Dimensional Arrays 7.1 Arrays in C One of the more useful features of C is the ability to create arrays for storing a collection of related.
Chapter 2 ARRAYS.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Lecture 4 on Data Structure Array. Prepared by, Jesmin Akhter, Lecturer, IIT, JU Searching : Linear search Searching refers to the operation of finding.
Advance Data Structure 1 College Of Mathematic & Computer Sciences 1 Computer Sciences Department م. م علي عبد الكريم حبيب.
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
CSC 211 Data Structures Lecture 13
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
Data Structure Introduction.
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Chapter 8 Search and Sort ©Rick Mercer. Outline Understand how binary search finds elements more quickly than sequential search Sort array elements Implement.
Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure.
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.
Sorting and Searching. Selection Sort  “Search-and-Swap” algorithm 1) Find the smallest element in the array and exchange it with a[0], the first element.
IN THE NAME OF ALLAH WHO IS THE MOST BENEFICENT AND MOST MERCIFUL.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Lecture No. 04,05 Sorting.  A process that organizes a collection of data into either ascending or descending order.  Can be used as a first step for.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Sorting and Searching by Dr P.Padmanabham Professor (CSE)&Director
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
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.
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
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.
Arrays. Arrays are objects that help us organize large amounts of information.
Lecture #15 ARRAYS By Shahid Naseem (Lecturer). 2 ARRAYS DEFINITION An array is a sequence of objects of same data type. The objects in an array are also.
Algorithms Chapter 3 With Question/Answer Animations
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Unit-2 Divide and Conquer
Searching and Sorting Arrays
Searching and Sorting 1-D Arrays
Data Structures (CS212D) Week # 2: Arrays.
Arrays Week 2.
ICS103: Programming in C Searching, Sorting, 2D Arrays
Presentation transcript:

Arrays Department of Computer Science

C provides a derived data type known as ARRAYS that is used when large amounts of data has to be processed. “ an Array is a fixed size sequenced collection of elements of the same data type” OR “ it is a sequenced collection of related data items that share a common name” Example: Array name student to represent a set of students in a class. The students can be referred individually by writing a number called Index or subscript in brackets [ ] followed by the array name. i.e. : students[50].

1- dimensional or single dimensional arrays: A list of items can be given with one variable name using only one subscript and such a variable is called as single subscripted variable or a one dimensional array For example : int number[4];refers to 4 memory (storage) locations, if we want to store the following numbers namely {10,20,30,40} then we have as shown in fig 2 number [0] number[1] number [2] number[3] number [0] number[1] number [2] number[3]

Declaration of 1- dimensional arrays Arrays must be declared before they are used. The general form of declaration is given by type variable-name[size]; Where the type specifies the data type of the element. size gives the maximum number of elements that can be stored Examples: int class[50]; float amount[20];

Initialization of 1- dimensional arrays Arrays must be initialized otherwise they refer to garbage values. The array can be initialized in the following 2 ways 1.At compile time 2.At run time Compile time initialization: type array-name[size]={list of values}; Where the values are seperated by commas. Examples: int number[5]={1,2,3,4,5}; If the number of values are less than the number of elements, the remaining elements will be set to zero automatically by the complier float amount[20];

Reading/ writing single dimensional arrays for(i=0; i< n; i++) scanf(“%d”,&a[i]); for(i=0; i< n; i++) printf(“%d”,a[i]);

Algorithm sum_of_pos_neg This algorithm calculates the sum of positive & negative numbers and the average of all the numbers. Step 1: [Start] Step 2: [Input the number of items] read n Step 3: [Read N elements from keyboard] for i=0 to n-1 read a[i] end for Step 4: [Initialization] psum=nsum=0 Step 5: [Find the sum of +ve and –ve no.s] for i=0 to n-1 in steps of 1 do if (a[i] >=0) psum=psum+a[i] else nsum=nsum+a[i] end for Step 6: [compute the average] avg=(psum+nsum)/n Step 7: [Output the sum] write(psum,nsum,avg) Step 8: [Finished] stop

Searching Searching is the process of finding the location of the specified element in a list. The specified element is often called the search key. If the process of searching finds a match of the search key with a list element value, the search is said to be successful ; otherwise, it is unsuccessful. The two most commonly used search techniques are: Sequential search [linear search] Binary search Sequential search [Linear search] A Linear search is a simple searching technique. In this technique we search for a given key item in the list in linear order i.e; one after the other. The item to be searched is often called key item.

For example: if key =10 and the list is 20,10,40,25 after searching we say that key is present. If key =100 after searching we say that key is not present. Procedure: let us take an example. Assume 10 is the item to be searched in the list of items 50,40,30,60,10. observe from above figure that, 10 has to be compared with a[0], a[1], a[2], a[3], and a[4] as shown below: During search if item ==a[0] or if item ==a[1] or if item ==a[2] or if item==a[3] or if item ==a[4] The search is successful for(i=0; i< 5; i++) { if (item==a[i]) { printf(“successful”); exit(0); }

Algorithm Linear_ search This algorithm is used to search for an item in a given list. Step 1: [Start] Step 2: [Input the number of items] read n Step 3: [Read N elements from keyboard] for i=0 to n-1 read a[i] end for Step 4:[Input the item to be searched] read key Step 5:[Search for the element to be searched (key)] for i=0 to n-1 if (key=a[i]) write(“successful”) stop end if end for write(“ unsuccessful”); Step 6: [Finished] stop

Advantages / Disadvantages of Linear Search: 1.Very simple. 2.Works well with small arrays/ when the size of the array is small. 3.Used when the elements are not sorted/ works when the array is unsorted. Disadvantages: 1.Not efficient / in efficient.

Binary Search Technique This searching technique requires the array to be in sorted order either in ascending or descending order. Procedure: This method divides the given array into 2 halves and considers that Portion in which the item (search element) is present. The above process is repeated until the item is located or the entire array is searched to find that item is not present

Binary Search Technique To locate the given key element in an array, the following variables are Used: 1. low = location of first element in the selected portion 2. mid= location of the middle element in the array (center) 3. high= location of the last element 4. key/item=search element 5. n = number of elements in the given array

Binary Search Technique Procedure: 1. Initialize variables low and high to 0 and n-1 low=0, high=n Find the middle element mid=(low+high)/2 3. Compare the key item with the element a[mid] at the middle of the array- the following possible situations arise a. if key < a[mid], then the key lies in the first half of the array, therefore low=0(remains the same) high=mid-1 b. if key > a[mid], then the key lies in the second half of the array, therefore low=mid+1 high=n-1(remains the same) c. if item=a[mid], then the key item is found and the location is equal to mid, STOP the searching process. 4. Repeat steps 2 & 3, until either the key item is found or until scanning of entire array is completed 5. If low > high, it indicates that the entire array has been scanned and the item is not present in the array, stop the scanning process

Let us take up a example in which an array a consists of 13 elements, where in the key item is 27(search element) Low =0 High=12 Mid1=(0+12)/2=6 i.e. 22

Since key item is 27 which is greater than the middle element, consider the second half of the array by setting low = mid1+1 = 7 and high=remains the same(12) Mid2=(low+high)/2 (7+12)/2=9 = 30 Since the key element is 27 which is < 30 Choose the first half of the array by making the following settings Low=remains the same (7) High= mid2-1=(9-1)=8

Mid3=(low+high)/2=(7+8)/2=7=25 Since the key element is 27 which is >25 Choose the second half of the array by making the following settings Low=mid3+1=7+1=8 High= remains the same=8

27 8 Mid4=(low+high)/2=(8+8)/2=8=27 Since the key element is 27 which is a[mid4]=27 The item is found

Bubble sort Technique This is the simplest of all sorting techniques that requires passing through the array sequentially several times. Thus while sorting an array in ascending order, the largest element is pushed to last location(n-1) after the first pass. Subsequent largest element is pushed to last but one location(n-2) after the second pass and so on. In general the Bubble Sort technique requires (n-1) passes to sort an array with n elements.

Bubble sort Technique – PASS 1 Consider an array of 5 elements that are to be sorted in ascending order, it requires 4 passes Exchange a[0] & a[1] since a[0] > a[1] Exchange a[1] & a[2] since a[1] > a[2] Exchange a[2] & a[3] since a[2] > a[3] Exchange a[3] & a[4] since a[3] > a[4] 1 st Largest element is at location 4

Bubble sort Technique – PASS Exchange a[0] & a[1] since a[0] > a[1] Exchange a[1] & a[2] since a[1] > a[2] Exchange a[2] & a[3] since a[2] > a[3] 2 nd Largest element is at location 3

Bubble sort Technique – PASS Exchange a[0] & a[1] since a[0] > a[1] Exchange a[1] & a[2] since a[1] > a[2] 3 rd Largest element is at location 2

Bubble sort Technique – PASS Exchange a[0] & a[1] since a[0] > a[1] The array is sorted in ascending order

Selection sort Technique In this method, successive elements chosen in order are placed into sorted positions.

Selection sort Technique The strategy given below is used to sort an array with n elements in descending order. 1.To place the largest element at location 0, find the location loc of the largest element in the array and exchange the elements a[0] & a[loc]. 2.To place the next largest element at location 1, find the location loc of the largest element among the succeeding elements from location 2 to location n-1 and swap the elements a[1] and a[loc]. The elements at locations i and loc are exchanged using the following Code: temp=a[i]; a[i]=a[loc]; a[loc]=a[i];

Selection sort Technique Consider an array a with the following elements a To place an appropriate element at location 0: Find the location loc of the largest element among the elements from locations 1 to n-1 and exchange the elements a[0] with a[loc] Initially let loc=0 swap a[0] & a[4] a [1] >a [loc] : loc=1 a [2] < a [loc] : loc remains as 1 a [3] > a [loc] : loc=3 a [4] > a [loc] : loc=4 a [5] < a [loc] : loc remains as

Selection sort Technique Let loc=1 swap a[1] & a[3] a [2] < a [loc] : loc remains as 1 a [3] > a [loc] : loc=3 a [4]< a [loc] : loc remains as 3 a [5] < a [loc] : loc remains as

Selection sort Technique Let loc=2 swap a[2] & a[5] a [3] > a [loc] : loc=3 a [4]< a [loc] : loc remains as 3 a [5] > a [loc] : loc =

Selection sort Technique Let loc=3 swapping not required a [4]< a [loc] : loc remains as 3 a [5] < a [loc] : loc =

Selection sort Technique Let loc=4 swap a[4] & a[5] a [5] > a [loc] : loc = Thus it can be seen that the array is sorted in descending order.

Horner’s Method – evaluation of a polynomial While evaluating a polynomial function numerous multiplications, additions etc are required. By writing the polynomial in a particular form the number of computations required can be reduced as shown below in a example The polynomial function requires 10 multiplications and 4 additions Given f(x)=10x 4 + 6x 3 + 4x 2 + 5x +20 The above polynomial can be re written as f(x)=(10x 3 + 6x 2 + 4x + 5)x +20 =((10x 2 + 6x + 4)x + 5)x+ 20 =(((10x+ 6)x+ 4)x+ 5)x+ 20. This requires / needs 4 multiplications and 4 additions

Horner’s Method – Procedure 1.Store the coefficients a0,a1,a2,…..an in the array [a]. 2.Store the successive values generated while evaluating the Horner’s series in the array [b], such as b[0] = a[0] b[1] = b[0] * x + a[1] b[2] = b[1] * x + a[2] b[3] = b[2] * x + a[3] b[n] = b[n-1] * x + a[n] The successive coefficients b[0], b[1], b[2]……….b[n], can be calculated using the for loop as given below b[0]=a[0]; for (i=1; i<n; i++) b[ i ] = b[ i-1 ] * x + a[ i ]

Mean, variance and Standard Deviation sum=0; for(i=0;i<n;i++) { sum=sum+x[i]; } mean=sum/n; Variance & Deviation can be calculated using: sum=0; for(i=0;i<n;i++) { sum=sum+(x[i]-mean) * (x[i]-mean); } variance=sum/n; deviation=sqrt(variance);

2-dimensional Arrays Arrays with 2 sets of square brackets [ ] [ ] are called 2 dimensional arrays 2-dimensional arrays are used when data items are arranged in row-wise and column wise in a tabular fashion. Declaration of 2 dimensional arrays data_type array name[exp1][exp2]; Where data type = basic data types Array name = name of the array exp1, exp2= constant expressions that are enclosed within square brackets and no variables are allowed. Ex: int a[3][4];

Reading & Writing 2- dimensional Arrays: /* read the elements of matrix*/ for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { scanf(“%d”,&a[ i ][ j ]); /* to read m x n */ }

Reading & Writing 2- dimensional Arrays: /* printing the elements of matrix*/ for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { printf(“%d ”,a[ i ][ j ]); /* to print m x n */ } printf(“\n”); }

Addition of 2 matrices a & b and storing the result in c for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { c[ i ][ j ]= a[ i ] [ j ] + b[ i ][ j ]; }

Subtract matrix b from a and storing the result in c for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { c[ i ][ j ]= a[ i ] [ j ] - b[ i ][ j ]; }

Sum of Elements of a given Matrix /* a[i ] [ j ] is added with sum whose value is initialized to 0 in the beginning */ sum=0; for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { sum= sum+ a[ i ] [ j ]; }

Transpose of a given Matrix /* let a & b be 2 matrices, matrix b is said to be the transpose of a when its rows and columns are interchanged */ i.e. a [ i ] [ j ]=b[ j ] [ i ] for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { b[ j ] [ i ] = a [ i ] [ j ]; }

Trace of a given Matrix /* The Trace of a matrix is the sum of the elements of principal diagonal elements in a given matrix – rectangular matrix */ sum = 0; for (i=0;i< n; i++) { sum = sum + a [ i ] [ i ]; }

Norm of a given Matrix /* The norm of a matrix is the square root of sum of the squares of all the elements in a given matrix */ sum = 0; for (i=0;i< m; i++) for (j=0;j< n; i++) sum = sum + a [ i ] [ j ] * a [ i ] [ j ] ; norm=sqrt(sum);

Product of 2 matrices a & b and storing the result in c /* multiplication of 2 matrices is possible iff the number of columns of first matrix and number of rows of the second matrix are same */ i.e. = let m x n be the size of the 1 st matrix and p x q be the size of the 2 nd matrix, if n=p then multiplication is possible */ for (i=0;i< m; i++) /* m rows */ { for (j=0;j< q; j++) /*n columns */ { sum=0; for (k=0;k< n; k++) { sum=sum + a[ i ] [ k ] * b[ k ][ j ]; } c[ i ][ j ]=sum; } If(n!=p) { printf(“ multiplication is not possible”); exit(0); } printf(“ multiplication is possible”);