Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 09 Strings, IDEs. METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan Mon July 29, 2002.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
ECE Application Programming Instructor: Dr. Michael Geiger Spring 2012 Lecture 31: PE5.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Pointers in C Rohit Khokher
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
Arrays Chapter 6.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Introduction to Computers and Programming Class 22 Character Arrays (Strings) Professor Avi Rosenfeld.
To remind us We finished the last day by introducing If statements Their structure was:::::::::
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
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.
C Arrays and Pointers In Java, pointers are easy to deal with –In fact, there is little that can go wrong in Java since pointer access is done for you.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
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
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
Chapter 8 Arrays and Strings
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Chapter 8 Arrays Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman CP 202 Chapter
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
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.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
Strings, Pointers and Tools
CSCI 130 More on Arrays. Multi-dimensional Arrays Multi - Dimensional arrays: –have more than one subscript –can be directly initialized –can be initialized.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
Multidimensional Arrays tMyn1 Multidimensional Arrays It is possible to declare arrays that require two or more separate index values to access an element.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 5 : September 4.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Computer Programming BCT 1113
Arrays in C.
Arrays and Records.
Arrays … The Sequel Applications and Extensions
Engineering Problem Solving with C++, Etter
Presentation transcript:

Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location of a particular value Find the student who got a ‘90’ –Sort an array to produce an ordered sequence of data values Arrange an array of student grades in increasing order (for example, when we want to print the list)

Array Search 4 In order to search an array, we need to know the array element we are seeking - the search target 4 Examine each array element using a loop, testing whether the array element is equal to the target 4 Exit the loop when the target is found: the result is the subscript of the array element 4 This process is called linear search

Linear Array Search Algorithm 1. Assume the target has not been found 2. Start with the intial array element 3. Repeat while the target is not found and there are more array elements 4. If the current element matches target 5. Set a flag to indicate found Else 6. Advance to the next array element 7. If the target was found 8. Return the index as search result Else Return -1 as the search result

Linear Search of an Array #define NOT_FOUND -1 int search(const, int arr[], int target, int n) { int i, found = 0, where; i = 0; while (!found && i < n) { if (arr[i] == target) found = 1; else ++i; }

Linear Search of an Array if (found) where = i; else where = NOT_FOUND; return(where); }

Sorting an Array 4 Many kinds of data processing are more efficient if the data is sorted before it is processed –Might this be the case for searching? 4 For this reason, much effort has been spent trying to develop efficient sorting algorithms –Selection sort is a simple (but not efficient) sorting algorithm

Selection Sort Algorithm 4 To perform a selection sort on an array with n elements –Locate the smallest element in the array and then switch the smallest element with the element at location 0 –Now locate the smallest element in the rest of the array (1..n-1) and place it at location 1 –Repeat the process for each subarray starting at location i (i=2..n-2)

Selection Sort Algorithm 1. For each value of fill from 0 to n-2 2. Find index_of_min, the index of the smallest element in the unsorted subarray list[fill] through list[n-1] 3. If fill is not the position of the smallest element (index_of_min) 4. Exchange the smallest element with the one at position fill

Selection Sort Program int get_min_range(int list[], int first, int last); void select_sort(int list[], int n) int fill, temp, index_of_min; for (fill = 0; fill < n-1; ++fill) { index_of_min = get_min_range(list, fill, n-1); if (fill != index_of_min) { temp = list[index_of_min];

Selection Sort Program list[index_of_min] = list[fill]; list[fill] = temp; }

Multidimensional Arrays 4 Multidimensional arrays are arrays which have two or more dimensions –Can represent tables, matrices, etc. –Most used is the two-dimensional array declared as follows char tictac[3][3]; –This two-dimensional array has three rows and three columns giving nine total elements –The first subscript gives the row, the second gives the column

Multidimensional Arrays 4 To specify an individual element we need two subscripts: tictac[2][2] = ‘x’; –When declaring a function that takes a two- dimensional array as as a parameter, we may leave out only the first dimension char tictac[][3]; –If we want, we may also give the first dimension char tictac[3][3];

Multidimensional Arrays 4 We may also have arrays with more than two dimensions int value[365][24][60][60]; 4 Multidimensional arrays may also be initialized as follows: char tictac[3][3] = {{‘ ‘,’ ‘,’ ‘},{‘ ‘, ‘ ‘,’ ‘},{‘ ‘,’ ‘,’ ‘}} 4 Multidimensional arrays can be processed by nested loops

Strings 4 The data type char can hold a single character 4 A sequence of characters is held by a data structure called a string –In C, the string data structure is implemented as an array of characters –Strings allow us to process textual data as well as numerical data –String processing in C is provided through standard libraries

Strings 4 A string literal is shown in double quotes (“This is a string”) while a character literal is shown in single quotes (‘c’) –We can’t assign string literals to character variables –We have seen strings as the first argument of the printf function 4 Strings are declared as arrays of characters Char string_var[30]; –Declares a string of no more than 30 characters

Strings 4 Strings may be initialized in the declaration char str[20] = “Initial value”; 4 The final character of a string is given the value ‘\0’ the null character which shows the string is finished –You must allow space for this final character! –What size array must we declare to hold the string “abc”?

Arrays of Strings 4 Since one string is an array of characters, a two dimensional array of characters is an array of strings: char names[NUM_PEOPLE][NAME_LEN]; 4 This can be initialized as follows char names[NUM_PEOPLE][NAME_LEN] = {“Joe”, “John”, “Jim”, “Jerry”}; 4 A string can be printed in a printf or read in a scanf by using a %s placeholder printf(“Topic: %s\n”, string_var);

Strings in printf and scanf 4 Note that we give just the name of the string to be printed, no subscript 4 In a scanf, we don’t need the address-of operator (&) since the name of the string indicates the address scanf(“%s %s”, name1, name2); 4 The strings name1 and name2 must be big enough to hold the strings we read in, otherwise a run-time error will occur!

String Library Functions 4 We have seen that we can initialize a string variable in the declaration, unfortunately, we cannot (ever!) set the value of a string using the assignment operator in the body of a function! 4 If we want to change the value of a string, we must use a library function from the string.h library

String Library Functions 4 The function strcpy makes a copy of a string (given as the second parameter) in the first parameter: strcpy(s1, “hello”); strcpy(s2, s1); –This function is used instead of the assignment statement for string variables –The function strncpy copies up to n characters from the second parameter (a string) to the first parameter strncpy(s1, “inevitable”, 5);

String Library Functions 4 The strncpy does not add a null character after the n characters are copied! 4 The function strcat concatenates the second parameter to the first parameter (note that there must be space avaliable, or a run-time error will occur) strcat(s1, “and more”); strcat(s2, s1); –The function strncat appends up to n characters of the second parameter to the first parameter (i.e. works like strncpy)

String Library Functions 4 The function strcmp compares two strings alphabetically –Returns 0 if the strings are equal –Returns a negative value if the first string should precede the second –Returns a positive value if the second string should precede the first string –The function strncmp compares the first n characters of two strings

String Library Functions 4 The function strlen returns the numbers of characters in a string, not counting the terminating null character 4 The function strcpy copies one string into another one - so the first string must have enough space available for the second one –Otherwise, the first string will be filled, and the rest of the second string will be written in the memory locations following that string