Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 1320 Search, Sort and Strings

Similar presentations


Presentation on theme: "CSE 1320 Search, Sort and Strings"— Presentation transcript:

1 CSE 1320 Search, Sort and Strings
Dr. Sajib Datta

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

3 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

4 Binary Search

5 #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;

6 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?

7 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)

8 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.

9 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?

10 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

11 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

12 An example Pick 4, compare with 10

13 An example Pick 10, compare with 9 Need to swap

14 An example

15 An example Pick 10, compare with 6 Need to swap

16 An example

17 An example Pick 10, compare with -1

18 An example Notice, that 10 is at the right position Now, repeat from the beginning

19 An example Compare 1st element with 2nd element

20 An example Compare 2nd element with 3rd element Swap needed

21 An example

22 An example Compare 3rd element with 4th element Swap needed

23 An example

24 An example 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.

25 An example Now, repeat from the beginning again. But remember, we only need to go up to 3rd this time.

26 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

27 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;

28 Online materials for next class
Array Array.htm Sorting and searching Sort/Catalog0280__Search-Sort.htm Time complexity d2=complexity1 complexity.pdf OfAlgs.pdf (advanced!)

29 Strings

30 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.

31 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

32 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

33 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

34 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.

35 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.

36 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.

37 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.

38 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.”

39 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’};

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

41 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‟.

42 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’

43 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"); }

44 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);

45 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.

46 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.

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

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


Download ppt "CSE 1320 Search, Sort and Strings"

Similar presentations


Ads by Google