CSE 1320 Search, Sort and Strings

Slides:



Advertisements
Similar presentations
CSE Lecture 3 – Algorithms I
Advertisements

Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
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.
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.
 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.
C Programming Strings. Array of characters – most common type of array in C  Let’s make them easier for use Denote the end of array using a special character.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
- SEARCHING - SORTING.  Given:  The array  The search target: the array element value we are looking for  Algorithm:  Start with the initial array.
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
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 8 CHARACTER AND STRINGS
CPT: Search/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to discuss searching: its implementation,
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
+ ARRAYS - SEARCHING - SORTING Dr. Soha S. Zaghloul updated by Rasha M. AL_Eidan 2015.
CSC 211 Data Structures Lecture 13
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
מערכים (arrays) 02 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 15 1 Department of Computer Science-BGU.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
© Oxford University Press All rights reserved. CHAPTER 6 STRINGS.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
Strings, Pointers and Tools
Computer Programming for Engineers
DATA TYPE, MEMORY, AND FUNCTION Dong-Chul Kim BioMeCIS UTA 2/18/
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
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.
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.
Dr. Sajib Datta Feb 21,  In the last class we discussed: ◦ Bubble sort  How it works  performance.
Functions Dr. Sajib Datta Functions A function is a self-contained unit of program code designed to accomplish a particular task. Some functions.
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.
Dr. Sajib Datta Feb 14,  Ordering elements in some way  For numeric data, ascending order is the most common  Lots of techniques for.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
Dr. Sajib Datta Sep 10,  #include  void main()  {  int a = 25;  int b = 0;  int c = -35;  if( a || b ) ◦ printf("Test1\n");  else.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
Dr. Sajib Datta  Ordering elements in some way  For numeric data, ascending order is the most common  Lots of techniques for sorting  These.
MULTI-DIMENSION ARRAY STRING Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Dr. Sajib Datta  char type technically is an integer type  Computer uses numeric codes to represent characters, and store characters as integers.
Dr. Sajib Datta Sep 8,  char type technically is an integer type  Computer uses numeric codes to represent characters, and store characters.
Introduction to Programming Using C Arrays. 2 Contents Arrays Subscripting.
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
1-d Arrays.
(Numerical Arrays of Multiple Dimensions)
INC 161 , CPE 100 Computer Programming
Lecture 8 String 1. Concept of strings String and pointers
CSE1320 Loop Dr. Sajib Datta
CS 108 Computing Fundamentals November 2, 2017.
Functions Dr. Sajib Datta
A First Book of ANSI C Fourth Edition
Module 2 Arrays and strings – example programs.
Functions Dr. Sajib Datta
Arrays in C.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Algorithm design and Analysis
Introduction to Search Algorithms
Software John Sum Institute of Technology Management
INC 161 , CPE 100 Computer Programming
Chapter 7 Arrays PROGRAMMING IN ANSI C.
Strings Dr. Soha S. Zaghloul updated by Rasha ALEidan
Chapter 8 Character Arrays and Strings
Searching.
ECE 103 Engineering Programming Chapter 25 C Strings, Part 1
String manipulation string.h library
Exercise Arrays.
CS-161 Computer Programming Lecture 15 & 16: Arrays II
Presentation transcript:

CSE 1320 Search, Sort and Strings Dr. Sajib Datta CSE@UTA

Binary Search Can make it faster. However, unlike linear search, binary search has a precondition The sequence must be sorted

Binary Search Strategy: Compare ‘x’ with the middle element. If equal, we found it Else If ‘x’ < middle element, we can discard the half of the elements; all elements that are greater than the middle element and middle element itself Now search in the remaining half of the array Similarly, if ‘x’ > middle element, we can discard the half of the elements; all elements that are smaller than the middle element and middle element itself

Binary Search

#include <stdio.h> #define ARRSIZE 7 int main(void) { int intarr[ARRSIZE], target, i, left, right, mid; printf("Please input %d integers which are sorted in the ascending order and a target value.", ARRSIZE); scanf("%d", &target); for(i = 0; i<ARRSIZE; i++) scanf("%d", &intarr[i]); } left = 0; right = ARRSIZE-1; while(left <= right) { mid = (left+right)/2; if(intarr[mid] == target) printf("The index of the target in the array is %d.\n", mid); break; } else if (target > intarr[mid]) left = mid + 1; else right = mid - 1; if(left > right) printf("The target is not in the array.\n"); return 0;

Binary Search How many comparisons on average? Each time ‘x’ is not found, we are taking the half of the remaining array If the array has size ‘n’, how many times we can slice it into half?

Assume you can compare at most ‘m’ times After 1st half: array size n/2 After 2nd half: array size n/4 After 3rd half: array size n/8 …. After m-th half: array size n/(2m) Since, the minimum array size is 1 [there has to be at least 1 element] n/(2m) = 1 => m = log2(n)

Performance So, in binary search, there are log2(n) comparisons. If you are given a sorted array of a million integers (220), Linear search can make a million comparison operations Binary search will make around 20 comparisons You will learn more on performance in algorithm classes. This is very important aspect of programming.

Practice problem You are given an array containing 9 integers, ranging from 1 to 10. Each number between 1 to 10 appears exactly once in the array, but unfortunately one of them is missing. Can you find the missing number?

Sort Ordering elements in some way For numeric data, ascending order is the most common Lots of techniques for sorting These techniques vary in performance both with runtime and usage of extra memory

Bubble sort Given a sequence of numbers, it compares adjacent numbers and swap them if necessary Repeats the above procedure until all numbers are in right place

An example 4 10 9 6 -1 Pick 4, compare with 10

An example 4 10 9 6 -1 Pick 10, compare with 9 Need to swap

An example 4 9 10 6 -1

An example 4 9 10 6 -1 Pick 10, compare with 6 Need to swap

An example 4 9 6 10 -1

An example 4 9 6 10 -1 Pick 10, compare with -1

An example 4 9 6 -1 10 Notice, that 10 is at the right position Now, repeat from the beginning

An example 4 9 6 -1 10 Compare 1st element with 2nd element

An example 4 9 6 -1 10 Compare 2nd element with 3rd element Swap needed

An example 4 6 9 -1 10

An example 4 6 9 -1 10 Compare 3rd element with 4th element Swap needed

An example 4 6 -1 9 10

An example 4 6 -1 9 10 Now, do we need the compare 4th with the 5th? We already know 5th element is the largest. This implies, what we have as the 4th element, it must be the second largest, and is already in the correct place.

An example 4 6 -1 9 10 Now, repeat from the beginning again. But remember, we only need to go up to 3rd this time.

What is happening inside… 1st iteration places the largest number in the correct place 2nd iteration places the second largest number in the correct place ….. …. i-th iteration places the i-th largest number in the correct place

Bubble sort #include<stdio.h> #define ARR_SIZE 8 int main(void) { int intarr[ARR_SIZE] = {23, 4, 12, 8, 22, 1, 54, 9}, i, j, tmp; for(i = 0; i<ARR_SIZE-1; i++) for(j = 0; j<ARR_SIZE-i-1; j++) if(intarr[j]>intarr[j+1]) tmp = intarr[j]; intarr[j] = intarr[j+1]; intarr[j+1] = tmp; } printf("The array sorted by Bubble Sort: "); for(i = 0; i< ARR_SIZE; i++) printf("%d ", intarr[i]); return 0;

Online materials for next class Array http://www.java2s.com/Tutorial/C/0140__Array/Catalog0140__ Array.htm Sorting and searching http://www.java2s.com/Tutorial/C/0280__Search- Sort/Catalog0280__Search-Sort.htm Time complexity http://community.topcoder.com/tc?module=Static&d1=tutorials& d2=complexity1 http://www.cs.toronto.edu/~vassos/teaching/c73/handouts/brief- complexity.pdf http://www.csd.uwo.ca/courses/CS1037a/notes/topic13_Analysis OfAlgs.pdf (advanced!)

Strings

String A string is a series of one or more characters, terminated by a null character. Example “I am at UTA” The double quotation marks are not part of the string. They just inform the compiler they enclose a string, just as single quotation marks identify a character.

String C does not have a string type. Characters in a string are stored in adjacent memory cells, one character per cell, and an array consists of adjacent memory locations, so placing a string in an array is quite natural. We use an array of chars for storing a string. We can declare this just like we did with other types. Example char letters[12] = “I am at UTA”; I a m t U T A \0

String \0 is the null character which is used by C for marking the end of a string The null character is not the digit zero; it is the nonprinting character. Its ASCII code value is 0. The presence of the null character means the array must have at least one more cell than the number of the characters to be stored

String Even though we define a char array much larger than a string, the null character will tell the compiler where is the end of the string. This is useful when we call printf( ). char letters[15] = “I am at UTA”; I a m t U T A \0

String gets() – read a line from input Reads characters from stdin and stores them as a string into str until a newline character ('\n'). The ending newline character ('\n') is not included in the string. A null character ('\0') is automatically appended after the last character copied to str to signal the end of the C string. Notice that gets() does not let you specify a limit on how many characters are to be read, so you must be careful with the size of the array pointed by str to avoid overflows.

gets(), puts() puts(the name of your char array) print out a string. #include <stdio.h> int main(void) { char myString[41]; //printf("Please intput a string with characters <= 40:\n"); puts("Please intput a string with characters <= 40:\n"); gets(myString); puts(myString); return 0; } Note that all input will be regarded as one string. However, scanf(“%s”, myString) will only read the characters until the first space as one string.

scanf(“%s”,…) Scan a string and print it out #include <stdio.h> int main(void) { char name[40]; printf("What's your name?\n"); scanf("%s", name); printf("Hello, %s.\n", name); return 0; } %s is the format specifier for a string. The name of a char array represents an address in computer memory, therefore, we don‟t need “&” when we call scanf function.

scanf() If your input is Sajib Datta Just calling scanf() once will only store Sajib in the char array as a string. The remaining of the input will be ignored. In this case, the space is used to separate strings in a sentence.

But with gets()… Scan a string and print it out #include <stdio.h> int main(void) { char name[40]; printf("What's your name?\n"); gets(name); printf("Hello, %s.\n", name); return 0; } If you input “Sajib Datta”, it will print “Hello Sajib Datta.”

Examples 1. char a[2] = {‘x’,’y’}; printf(“%s”, a); // puts(a); 2. char a[3] = {‘x’,’y’}; printf(“%s”,a); //puts(a); 3. char a[2] = “xy”; 4. char a[3] = “xy”; 5. char a[5] = {‘’x’,’y’,’z’,’\0’,’d’};

Examples 6. char a[5] = “xyz\0d”; printf(“%s”,a); //puts(a); 7. char a[5] = “xy\\0”;

Length of the string #include <stdio.h> #include <string.h> int main(void) { char text[100]; int size, i; printf("Enter a string: "); scanf("%s", text); printf("you entered %s\n", text); size = strlen( text ); printf("The number of characters in the input string is %d.\n", size); return 0; } The strlen function returns the number of characters in a string, excluding “\0‟.

Working with strings Now if we access all characters of a string in a loop, we have two approaches to terminate the loop: (1) the length of the string ---- strlen() (2) ‘\0’

Working with strings Print out the reversed string #include <stdio.h> #include <string.h> int main(void) { char text[100]; int size, i; printf("Enter a string: "); scanf("%s", text); printf("you entered %s\n", text); size = strlen( text ); for(i = size - 1; i >= 0; i--) printf("%c", text[i]); printf("\n"); }

Count uppercase/lowercase #include <stdio.h> #include <string.h> int main(void) { char text[100]; int size, i, upper = 0, lower = 0; printf("Enter a string: "); scanf("%s", text); size = strlen( text ); for(i = 0; i < size; i++) if('A' <= text[i] && text[i] <= 'Z') upper++; else if('a' <= text[i] && text[i] <= 'z') lower++; } printf("upper = %d, lower = %d\n", upper, lower);

String compare strcmp(str1, str2) This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.

strcmp() A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.

#include <stdio.h> #include <string.h> int main(void) { char str1[] = "cat", str2[] = "car"; printf("%d", strcmp(str1, str2)); return 0; }

#include <stdio.h> #include <string.h> int main(void) { char str1[] = "catp", str2[] = "carw"; printf("%d", strcmp(str1, str2)); return 0; }