.. _basic-searching: Searching and Sorting ##################### We have two basic data structures available now: the Array, and a Linked List. These are great for saving many data items, but we need to look at a few ways to use the data once it is in one of these things. Searching ********* The basic tool to searching a data structure is the loop. Lets start by finding the biggest and smallest element in a simple array. Here is the basic program: Searching for an Integer ======================== Here is what we want to do (this should look familiar): .. code-block:: c #include using namespace std; #define NUMSCORES 7 int searchMin(int list[], int size); int searchMax(int list[], int size); int main() { int testScores[] = { 90,67,86,88,98,69,72}; int minScore; int maxScore; minScore = searchMin(testScores,NUMSCORES); maxScore = searchMax(testScores,NUMSCORES); cout << "min = " << minScore << " max = " << maxScore << endl; } Finding min and max =================== You gave this problem a try in an earlier lab. Let's revisit the idea again. The challenge is to figure out how to locate the required elements in the lists. We solve this problem by looping over all the items in the Array (or list). As you start, you have no items in hand. When you look at the first item it is both the biggest and the smallest seen so far, so we set a variable to this value (as either biggest or smallest depending on what you are looking for). Then we enter a loop looking at the rest of the items doing a comparison and replacing our current selection if needed. .. code-block:: c int searchMin(int list[], int size) { int min = list[0]; for(int i=1;i max) max = list[i]; } return max; } Running this example gives us this result: .. code-block:: text $ search min = 67 max = 98 That was not very hard, was it? Finding an Element ================== If we want to know if some item is in the list, we again need to search all the elements, since we do not know where it might be. Here is a routine to find an element .. code-block:: c bool findItem(int list[], int size, int item) { bool found = false; for(int i=0;i max) { max = list[i]; index = i; } } return index; } This look very similar to the search routine we had earlier. Now, we need to work our way through the array, using this routine, and swapping elements. You will need to study this code and see how it works. Can you make it simpler? Sorting Routine --------------- .. code-block:: c void sortArray(int list[], int size) { for(int i=0;i