ICS103: Programming in C Searching, Sorting, 2D Arrays

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

CSE Lecture 3 – Algorithms I
CHAPTER 10 ARRAYS II Applications and Extensions.
CS0007: Introduction to Computer Programming Array Algorithms.
Dr. Sajib Datta  We can also have arrays of arrays, also known as multidimensional arrays.  E.g., A two-dimensional array is an array of several.
1 ICS103 Programming in C Lecture 16: 2-Dimensional Arrays.
Sorting and Searching. Searching List of numbers (5, 9, 2, 6, 3, 4, 8) Find 3 and tell me where it was.
1 ICS103 Programming in C Lecture 14: Searching and Sorting.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
1 Searching Algorithms Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Searching Arrays Linear search Binary search small arrays
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Chapter 8 Arrays and Strings
1 Two-Dimensional Arrays. 2 Can be visualized as consisting m rows, each of n columns Syntax: datatype arrayname [row] [ column] ; Example: int val[3]
- SEARCHING - SORTING.  Given:  The array  The search target: the array element value we are looking for  Algorithm:  Start with the initial array.
1 ICS103 Programming in C Ch7: Arrays. O BJECTIVES What is an Array? Declaring Arrays Visual representation of an Array Array Initialization Array Subscripts.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
Chapter 8 Arrays and Strings
1 Searching. 2 Searching Searching refers to the operation of finding an item from a list of items based on some key value. Two Searching Methods (1)
SEARCHING UNIT II. Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances.
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
CS 162 Intro to Programming II Searching 1. Data is stored in various structures – Typically it is organized on the type of data – Optimized for retrieval.
SEARCHING. Vocabulary List A collection of heterogeneous data (values can be different types) Dynamic in size Array A collection of homogenous data (values.
+ ARRAYS - SEARCHING - SORTING Dr. Soha S. Zaghloul updated by Rasha M. AL_Eidan 2015.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman CP 202 Chapter
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
CSC 211 Data Structures Lecture 13
1 ICS103 Programming in C Lecture 14: Searching and Sorting.
CSE 251 Dr. Charles B. Owen Programming in C1 Pointers, Arrays, Multidimensional Arrays Pointers versus arrays – Lots of similarities How to deal with.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
Data Structure Introduction.
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
Chapter 8 Arrays Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
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.
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.
Arrays Why we need data structure? Simple data types use a single memory cell to store a variable. Sometimes (for example scores of a class) it is more.
IN THE NAME OF ALLAH WHO IS THE MOST BENEFICENT AND MOST MERCIFUL.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
ICS103: Programming in C Searching, Sorting, 2D Arrays Muhamed F. Mudawar.
Structured Programming Approach Module VIII - Additional C Data Types Arrays Prof: Muhammed Salman Shamsi.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
CS212: DATASTRUCTURES Lecture 3: Searching 1. Lecture Contents  searching  Sequential search algorithm.  Binary search algorithm. 2.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
ICS103: Programming in C 7: Arrays Muhamed F. Mudawar.
Chapter 3: Sorting and Searching Algorithms 3.1 Searching Algorithms.
Dr. Sajib Datta Feb 11,  Example of declaring and initializing an array. ◦ double someData[3]; /* declare the array someData that will.
Dr. Sajib Datta CSE 1320 Arrays, Search and Sort.
Arrays and Matrices. One-Dimensional Arrays An array is an indexed data structure All variables stored in an array are of the same data type An element.
 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.
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.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Dr. Sajib Datta Sep 10,  #include  void main()  {  int a = 25;  int b = 0;  int c = -35;  if( a || b ) ◦ printf("Test1\n");  else.
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
ICS103 Programming in C Lecture 14: Searching and Sorting
Programming application CC213
Arrays and Records.
Arrays … The Sequel Applications and Extensions
Review of Arrays and Pointers
Data Structures (CS212D) Week # 2: Arrays.
Arrays Week 2.
ICS103: Programming in C Searching, Sorting, 2D Arrays
Presentation transcript:

ICS103: Programming in C Searching, Sorting, 2D Arrays Muhamed F. Mudawar

Outline Searching: Linear and Binary Search Sorting: Selection Sort 2D Arrays

Searching Traversing an array to locate a particular item It requires the user to specify the target item If the target item is found, its index is returned If the target item is NOT found, -1 is returned Two searching algorithms Linear Search (works with any array) Binary Search (works if the searched array is sorted)

Linear Search Algorithm Assume that the target has not been found Start with initial array element Repeat while the target is not found and there are more array elements If the current element matches the target Set a flag to indicate that the target was found Else, Advance to the next array element If the target was found Return the target index as the search result Else, Return -1 as the search result

Linear Search Implementation /* Search array a[] for target using linear search * Returns index of target or -1 if not found */ int linear_search(const int a[], int target, int n) { int i = 0, found = 0; while (!found && i<n) { if (a[i] == target) found = 1; else ++i; } if (found) return i; else return -1; For an array of n elements, linear search uses an average of n/2 comparisons to find an item. The worst case being n comparisons.

Binary Search Algorithm If an array is ordered, it is a waste of time to look for an item using linear search. It would be like looking for a word in a dictionary sequentially. Binary search works by comparing the target with the item at the middle of the array: If the target is the middle item, we are done. If the target is less than the middle item, we search the first half of the array. If the target is bigger than the middle item, we search the second half of the array. Repeat until target is found or nothing to search

Binary Search first mid last 5 11 target = 22 4 7 8 10 14 21 22 36 54 71 85 92 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] first mid last 6 8 11 4 7 10 14 21 22 36 54 71 85 92 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] 22>21 first mid last 6 7 4 8 10 14 21 22 36 54 71 85 92 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] 22<54 22==22

Binary Search Implementation int binary_search (int a[], int target, int n) { int first=0, last=n-1, mid; while (first <= last) { /* more to search */ mid = (first + last)/2; if (target == a[mid]) return mid; /* target found */ else if (target < a[mid]) last = mid – 1; else first = mid + 1; } return -1; /* target not found */

Next . . . Searching: Linear and Binary Search Sorting: Selection Sort 2D Arrays

Sorting Sorting is the ordering of a collection of data It is a common activity in data management Many programs execute faster if the data they process are sorted before processing begins Other programs produce more understandable output if the data displayed is sorted Many sorting algorithms have been designed We shall consider the Selection Sort method.

Selection Sort Algorithm Find the index of the smallest element in the array. Swap the smallest element with the first element. Repeat for the 2nd, 3rd, …next smallest element.

Selection Sort Function */

Smallest Element in Sub-Array /* Find the smallest element in the sub-array list[first] * through list[last], where first<last * Return the index of the smallest element in sub-array */ int get_min_range(int list[], int first, int last) { int i; int index_min = first; for (i=first+1; i<=last; i++) { if (list[i] < list[index_min]) index_min = i; } return index_min;

Next . . . Searching: Linear and Binary Search Sorting: Selection Sort 2D Arrays

Two-Dimensional Arrays A 2D array is a contiguous collection of elements of the same type, that may be viewed as a table consisting of multiple rows and multiple columns. To store the grades of 30 students in five courses, it is better to use a 2D array than five 1D arrays. Column Row 1 2 3

2D Array Declaration A 2D array is declared by specifying the type of element, the name of the variable, followed by the number of rows and the number of columns As with 1D arrays, it is a good practice to declare the row and column sizes as named constants: #define ROWS 3 #define COLS 4 . . . int table[ROWS][COLS]; Both rows and columns are indexed from zero. Column Row 1 2 3

Indexing 2D Arrays A 2D array element is indexed by specifying its row and column indices. The following statement stores 64 in the cell with row index 1, and column index 3: table[1][3] = 51; Here is another example: table[2][3] = table[1][3] + 6; 1 2 51 3 1 2 51 57 3

It is ok to omit the number of rows but not the number of columns Initializing 2D Arrays As with 1-D arrays, you can declare and initialize a 2D array at the same time. A nested list is used, where each inner list represents a row. For example: int table[][4] = {{1,2,2,5},{3,4,6},{5,6,7,9}}; If you provide less values than the declared size, the remaining cells are set to zero 1 2 3 5 4 6 7 9 It is ok to omit the number of rows but not the number of columns

Processing 2D Arrays To process a 2D array, we use a nested loop, and traverse the 2D array either row-wise or column-wise To process the elements row-wise, we write: for (i = 0; i < ROWS; i++) for(j = 0; j < COLS; j++) { /* process table[i][j] */ } To process the elements column-wise, we write: for (j = 0; j < COLS; j++) for(i = 0; i < ROWS; i++) {

Program to Add 2D Arrays #include <stdio.h> #define ROWS 10 /* maximum number of rows */ #define COLS 10 /* maximum number of cols */ void read_2d (double a[][COLS], int r, int c); void add_2d (double a[][COLS], double b[][COLS], double s[][COLS], int r, int c); void print_2d(double a[][COLS], int r, int c);

2D Array As a Parameter As with 1D arrays, it is possible to declare a function that takes a 2D array as a parameter. The size of the first dimension (number of rows) need not be specified in the 2D array parameter. However, the size of the second dimension (columns) must be specified as a constant. One solution is to use a named constant defining the maximum number of columns and use additional parameters for the actual size of the 2D array: void read_2d(double a[][COLS], int r, int c);

Function to Read a 2D Array void read_2d (double a[][COLS], int r, int c) { int i, j; printf("Enter a table with %d rows\n", r); printf("Each row having %d numbers\n", c); for (i=0; i<r; i++) for (j=0; j<c; j++) scanf("%lf", &a[i][j]); }

int main(void) { double x[ROWS][COLS], y[ROWS][COLS], z[ROWS][COLS]; int rows, cols; printf("Enter number of rows: "); scanf("%d", &rows); printf("Enter number of columns: "); scanf("%d", &cols); read_2d(x, rows, cols); /* read matrix x */ read_2d(y, rows, cols); /* read matrix y */ add_2d(x, y, z, rows, cols); /* Add x + y */ printf("The sum of two matrices is:\n"); print_2d(z, rows, cols); /* Print matrix z */ return 0; } Main Function

Function to Add Two 2D Arrays void add_2d (double a[][COLS], double b[][COLS], double s[][COLS], int r, int c); int i, j; for (i=0; i<r; i++) for (j=0; j<c; j++) s[i][j] = a[i][j] + b[i][j]; }

Function to Print a 2D Array void print_2d(double a[][COLS], int r, int c) { int i, j; for (i=0; i<r; i++) { for (j=0; j<c; j++) printf("%6.1f", a[i][j]); printf("\n"); }

Sample Run . . .