Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location."— Presentation transcript:

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

2 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

3 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

4 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; }

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

6 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

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

8 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

9 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];

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

11 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

12 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];

13 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

14 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

15 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

16 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”?

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

18 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!

19 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

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

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

22 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

23 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


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

Similar presentations


Ads by Google