Searching and Sorting an Array 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)
23
Embed
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Searching and Sorting an Array
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
In order to search an array, we need to know the array element we are seeking - the search target
Examine each array element using a loop, testing whether the array element is equal to the target
Exit the loop when the target is found: the result is the subscript of the array element
This process is called linear search
Linear Array Search Algorithm1. 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
Many kinds of data processing are more efficient if the data is sorted before it is processed– Might this be the case for searching?
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
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
Multidimensional arrays are arrays which have two or more dimensions– Can represent tables, matrices, etc.– Most used is the two-dimensional array declared as
followschar 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
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 dimensionchar tictac[3][3];
Multidimensional Arrays
We may also have arrays with more than two dimensions
int value[365][24][60][60];
Multidimensional arrays may also be initialized as follows:
char tictac[3][3] = {{‘ ‘,’ ‘,’ ‘},{‘ ‘,
‘ ‘,’ ‘},{‘ ‘,’ ‘,’ ‘}}
Multidimensional arrays can be processed by nested loops
Strings
The data type char can hold a single character 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
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
Strings are declared as arrays of charactersChar string_var[30];
– Declares a string of no more than 30 characters
Strings
Strings may be initialized in the declarationchar str[20] = “Initial value”;
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
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];
This can be initialized as followschar names[NUM_PEOPLE][NAME_LEN] = {“Joe”, “John”, “Jim”, “Jerry”};
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
Note that we give just the name of the string to be printed, no subscript
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);
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
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!
If we want to change the value of a string, we must use a library function from the string.h library
String Library Functions
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
The strncpy does not add a null character after the n characters are copied!
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
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
The function strlen returns the numbers of characters in a string, not counting the terminating null character
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