ARRAYS Lecture 12 27.2.2001..

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

CSE Lecture 3 – Algorithms I
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
O-1 University of Washington Computer Programming I Lecture 14: Arrays © 2000 UW CSE.
O-1 University of Washington Computer Programming I Lecture 14: Arrays © 2000 UW CSE.
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.
1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======
1 Sorting Algorithms (Basic) Search Algorithms BinaryInterpolation Big-O Notation Complexity Sorting, Searching, Recursion Intro to Algorithms Selection.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Program structure Four different storage-class specifications: –Automatic (auto): local to a function, normally declared variables are automatic. Does.
Searching an Array: Linear and Binary Search Spring 2013Programming and Data Structure1.
P-1 University of Washington Computer Programming I Lecture 15: Linear & Binary Search ©2000 UW CSE.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
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.
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.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
CSE 251 Dr. Charles B. Owen Programming in C1 Intro to Arrays Storing List of Data.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
ARRAYS Lecture void reverse (int x[], int size) { int i; for (i=0; i< (size/2); i++) temp = x[size-i-1] ; x[size-1-1] = x[i] ; x[i] = temp;
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Recursion Riley Chapter 14 Sections 14.1 – 14.5 (14.6 optional)
Programming and Data Structures
1-d Arrays.
COP 3503 FALL 2012 Shayan Javed Lecture 15
Lecture 14 Searching and Sorting Richard Gesick.
Computer Programming BCT 1113
Lecture 7 Arrays 1. Concept of arrays Array and pointers
Chapter 9: Searching, Sorting, and Algorithm Analysis
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Sorting and Searching Sudeshna Sarkar 7th Feb 2017.
CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)
Object-Oriented Programming Using C++
Arrays … The Sequel Applications and Extensions
Programming and Data Structure
C Arrays.
Chapter 7 Single-Dimensional Arrays
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
7 Arrays.
Review for Final Exam.
Lecture 11 Searching and Sorting Richard Gesick.
Arrays Outline Introduction Arrays Declaring Arrays
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Searching and Sorting 1-D Arrays
Searching CLRS, Sections 9.1 – 9.3.
Data Structures (CS212D) Week # 2: Arrays.
Chapter 7 Single-Dimensional Arrays and C-Strings
Initializing variables
Engineering Problem Solving with C++, Etter
Review for Final Exam.
7 Arrays.
Algorithmic complexity
CS-161 Computer Programming Lecture 15 & 16: Arrays II
COMS 261 Computer Science I
ARRAYS ..
Intro to Arrays Storing List of Data.
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
Module 8 – Searching & Sorting Algorithms
Presentation transcript:

ARRAYS Lecture 12 27.2.2001.

Add an element in the front: Shifting an array /* Shift x[0],x[1], ... ,x[n-1] one position upwards (rightwards)to make space for a new element at x[0] Insert the value newval at x[0], update size */ int x[MAX], size, i; . . . for (i=size; i>=1; i=i-1) x[i] = x[i-1]; x[0] = newval; size++;

Shifting Array Elements 4 7 5 ? size = 3; newval = 0; 5 4 7 5 5 4 7 7 4 7 5 4 4 7 5

Delete the ith element of the array: shift left /* Shift x[i+1], ... , x[n-1], one position to the left thus deleting item x[i] */ for (k=i; k<(size-1); k++) x[k] = x[k+1]; size = size-1; size = 6 1 2 3 4 5 6 1 2 4 4 5 6 1 2 4 5 5 6 size = 5 1 2 4 5 6 6

Array Initialization int marks[10] = {10,8,7,9,6,10,6,7,8,8} marks has size 4, all values are initialized char vowels[6] = {'a','e','i'} vowels has size 6, only 3 values are initialized. Can not use this notation in assignment statement. Int w[10]; w = {1,2,3,4}; Syntax error double x[] = {1.2,3.4,8.1,0.9} /* x has size 4, all values initialized */ double x[]; Illegal

Passing array elements to functions Array element can be passed to functions as ordinary arguments. IsFactor (x[i], x[0]) sin (x[5])

Passing Arrays to a Function An array name can be used as an argument to a function. Permits the entire array to be passed to the function. The way it is passed differs from that for ordinary variables. Rules: The array name must appear by itself as argument, without brackets or subscripts. The corresponding formal argument is written in the same manner. Declared by writing the array name with a pair of empty brackets.

Whole array as Parameters #define ASIZE 200 double average (int a[]) { int i, total=0; for (i=0; i<ASIZE; i++) total = total + a[i]; return ((double) total / (double) ASIZE); } fun (. . .) { int x[ASIZE] ; double x_avg; . . . x_avg = average (x) ;

Arrays as Output Parameters void VectorSum (int a[], int b[], int vsum[], int length) { int i; for (i=0; i<length; i=i+1) vsum[i] = a[i] + b[i] ; } int main (void) { int x[3] = {1,2,3}, y[3] = {4,5,6}, z[3]; VectorSum (x, y, z, 3) ; PrintVector (z, 3) ; void PrintVector (int a[], int length) { for (i=0; i<length; i++) printf (“%d “, a[i]);

The Actual Mechanism When an array is passed to a function, the values of the array elements are not passed to the function. The array name is interpreted as the address of the first array element. The formal argument therefore becomes a pointer to the first array element. When an array element is accessed inside the function, the address is calculated using the formula stated before. Changes made inside the function are thus also reflected in the calling program.

Array operations } int readarray (int x[], int size) { int i; for (i=0; i<size; i++) scanf(“%d”, &x[i]) ; return size; } #define MAXS 100 int insert (int[], int, int, int) ; int delete (int[], int, int) ; int getelement (int[], int, int) ; int readarray (int[], int) ; main () { int a[MAXS]; int size; size = readarray (a, 10) ; size = insert (a, size, 4, 7) ; x = getelement (a, size, 3) ; size = delete (a, size, 3) ; } int getelement (int x[], int size, int pos){ if (pos <size) return x[pos] ; return -1; } int insert (int x[], int size, int pos. int val){ for (k=size; k>pos; k--) x[k] = x[k-1] ; x[pos] = val ; return size+1; }

void reverse (int x[], int size) { int i; for (i=0; i< (size/2); i++) temp = x[size-i-1] ; x[size-1-1] = x[i] ; x[i] = temp; } int findmax (int x[], int size) { int i, max; max = x[0]; for (i=1; i< size; i++) if (x[i] > max) max = x[i] ; return max; }

Strings Strings are 1-dimensional arrays of type char. By convention, a string in C is terminated by the end-of-string sentinel \0, or null character. String constant : “abc” is a character array of size 4, with the last element being the null chaaracter \0. char s[] = “abc” ; a b c \0

Searching an Array: Linear and Binary Search

Searching Check if a given element (key) occurs in the array. If the array is unsorted : start at the beginning of the array inspect every element to see if it matches the key

Linear Search /* If key appears in a[0..size-1], return its location, pos, s.t. a[pos] == key. If key is not found, return -1 */ int search (int a[], int size, int key) { int pos = 0; while (pos < size && a[pos] != key) pos++; if (pos<n) return pos; return -1; }

Linear Search int x= {12,-3, 78,67,6,50,19,10} ; Trace the following calls : search (x, 8,6) ; search (x,8,5) ;

Searching a sorted array Binary search works if the array is sorted Look for the target in the middle If you don’t find it, you can ignore half of the array, and repeat the process with the other half.

Binary Search Strategy What we want : Find split betwen values larger and smaller than x : L R x: <=key >key n Situation while searching : L R n x: <=key ? >key Step : Look at [(L+R)/2]. Move L or R to the middle depending on test.

Binary Search /* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key) { int L, R, mid; ______________________; while (_________________) { } ____________________ ;

Binary Search mid = (L+R)/2; if (x[mid] <= key) L = mid; /* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key) { int L, R, mid; ______________________; while (_________________) { mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } ____________________ ; mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid;

Binary Search: loop termination /* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key) { int L, R, mid; ______________________; while (_________________) { mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } ____________________ ; L+1 != R

Binary Search: Return result /* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key) { int L, R, mid; ______________________; while ( L+1 != R) { mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } if (L>=0 && x[L]==key) return L; else return -1;

Binary Search: Initialization /* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key) { int L, R, mid; ______________________; while ( L+1 != R) { mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } if (L>=0 && x[L]==key) return L; else return -1; L=-1; R=size;

Binary Search Examples -17 -5 3 6 12 21 45 63 50 Trace : binsearch (x, 9, 3); binsearch (x, 9, 145); binsearch (x, 9, 45);

Is it worth the trouble ? Suppose you had 1000 elements Ordinary search (if key is a member of x) would require 500 comparisons on average. Binary search after 1st compare, left with 500 elements after 2nd compare, left with 250 elements After at most 10 steps, you are done. What if you had 1 million elements ?

Sorting Given an array x[0], x[1], ... , x[size-1] reorder entries so that x[0]<=x[1]<= . . . <=x[size-1]

Sorting Problem What we want : Data sorted in order size x: sorted : x[0]<=x[1]<= . . . <=x[size-1] size x: Initial conditions : size x: unsorted

Selection Sort General situation : k size x: Step : k size x: smallest elements, sorted remainder, unsorted Step : Find smallest element, mval, in x[k..size-1] Swap smallest element with x[k], then increase k. k mval size x: smallest elements, sorted

Subproblem : : /* Yield location of smallest element int[x] in x[0 .. size-1];*/ int min_loc (int x[], int , int size) int j, pos; /* x[pos] is the smallest element found so far */ pos = k; for (j=k+1; j<size; j++) if (x[i] < x[pos]) pos = j; return pos; }

Selection Sort /* Sort x[0..size-1] in non-decreasing order */ int selsort (int x[], int size) { int k, m; for (k=0; k<size-1; k++) { m = min_loc(x, k, size); temp = a[k]; a[k] = a[m]; a[m] = temp; }

Example x: 3 12 -5 6 142 21 -17 45 x: -17 -5 3 6 12 21 142 45 x: -17 12 -5 6 142 21 3 45 x: -17 -5 3 6 12 21 45 142 x: -17 -5 12 6 142 21 3 45 x: -17 -5 3 6 142 21 12 45 x: -17 -5 3 6 12 21 142 45

Analysis How many steps are needed to sort n things ? Total number of steps proportional to n2

Insertion Sort #define MAXN 100 void InsertSort (int list[MAXN], int size) ; main () { int index, size; int numbers[MAXN]; /* Get Input */ size = readarray (numbers) ; printarray (numbers, size) ; InsertSort (numbers, size) ; }

void InsertSort (int list[], int size) { for (i=1; i<size; i++) item = list[i] ; for (j=i-1; (j>=0)&& (list[j] > i); j--) list[j+1] = list[j]; list[j+1] = item ; }

Common pitfalls with arrays in C Exceeding the array bounds int array[10]; for (i=0; i<=10; i++) array[i] = 0; C does not support array declaratiions with variable expressions. void fun (int array, int size) { int temp[size] ; . . . }