
FINDING A DATA ITEM THE SEARCH PROBLEM File sortsrchc include stdioh include sortsrchh define DEBUG Linear or sequential search of an array x of size lim for an item key int seqsrchint x int lim int key int i foriilimi if xi key returni return Figure Co de for the function seqsrch File sortsrchh This file contains prototypes for sort and search functions int seqsrchint x int lim int key Figure Initial contents of sortsrchh We will implement the algorithm for search as a function seqsrch since searching an array may b e required in many programs and a function incorp orating linear search can b e used for many applications The function is passed the arrayofintegers xthenumb er of elements in the array limandthekey to searchforkey The function is shown in Figure The lo op compares each elementofthearraywithkey If an element with the same value is found at an index i i is returned The lo op terminates when the array limit is reached in which case no element equal to key was found in the array and is returned If there is more than one element in the array with the same value as key the function terminates the searchassoon as the rst element is found returning its index Wehave dened DEBUG in sortsrchc so that debug statements wemay add to the co de will b e compiled Wehave also included le sortsrchh in sortsrchc which as shown in Figure contains the prototyp es for functions dened in sortsrchc since some of the functions dened in sortsrchc may b e used by other functions to b e written in the le Wewillcontinue to add more functions to sortsrchc and corresp onding prototyp es to sortsrchh as we pro ceed through this chapter however we will not always show the additions of prototyp es to sortsrchh Our task now requires us to write a simple driver to rep eatedly call the function seqsrch For simplicitywe will declare an initialized array The driver uses a function pr aray lineto CHAPTER SORTING AND SEARCHING print an array with ten elements p er line to save space Figure shows the program driver The driver rst prints an initialized array id and then searches for items entered by the user If an item is found in the array its index is printed Otherwise a message is printed The aray line is included in sortsrchc and its prototyp e in sortsrchh These function pr additions are shown in Figure The function prints at successiveelements on one line until the array index mo dulo is zero when it prints a newline and continues A sample session for the program srcharayc is shown b elow Sequential Search The id array is Type an integer EOF to quit Item is not in the array Type an integer EOF to quit Item is found at index Type an integer EOF to quit Item is found at index Type an integer EOF to quit D Improving Search Sorting the Data As wementioned ab ove linear searchmay b e useful when the number of elements is small however when there are many data items in the array linear searchmay require a long time to nd the element matching the key In the case where suchanelement is not in the data base wemust search the entire collection to nd that out Consider the phone b o ok again When wewantto lo ok up someones phone number we do not start at the b eginning of the b o ok and lo ok line by line until we nd the name Instead we make use of the fact that the data items are sorted by name in the phone b o ok Of course if we had a phone numb er and wanted to nd the name we would hav e to resort to linear searchwe do not often do that Before wedevelop an algorithm to conduct a more ecient search of sorted data we rst describ e several algorithms which will sort an array of data There are numerous ways to sort data some more suitable than others for dierent applications In this section we will describ e three dierent standard algorithms selection sort bubble sort and insertion sort Selection Sort The idea of selection sort is rather simple we rep eatedly nd the next largest or smallest element in the arrayandmove it to its nal p osition in the sorted array Assume that we wish to sort the array in increasing order ie the smallest element at the b eginning of the array and the largest element at the end We b egin by selecting the largest elementandmoving it to the highest index IMPROVING SEARCH SORTING THE DATA Filesrcharayc Other Source Files sortsrchc Header Files sortsrchh This program searches an array sequentially for items typed in by the user It prints out the array index where an item is found or else prints a message include stdioh include sortsrchh main int id int n i printfSequential Searchnn printfThe array isn praraylineid printfType an integer EOF to quit while scanfd n EOF i seqsrchidn if i printfItem d is found at index dn n i else printfItem d is not in the arrayn n printfType an integer EOF to quit Figure Driver to test seqsrch CHAPTER SORTING AND SEARCHING File sortsrchc continued Prints an array horizontally void praraylineint x int lim int i foriilimi if i printfn printfd xi printfn File sortsrchh continued void praraylineint x int lim Figure Adding the co de for pr aray line p osition We can do this byswapping the element at the highest index and the largest element We then reduce the eective size of the arrayby one element and rep eat the pro cess on the smaller subarray The pro cess stops when the eective size of the array b ecomes an array of element is already sorted For example consider the following arrayshown with arrayelements in sequence separated by commas The leftmost element is at index zero and the rightmost element is at the highest array index in our case the eective size of our array is The largest element in this eectivearray index is at index Wehaveshown the largest element and the one at the highest index in bold We then swap the element at index with that at index The result is We reduce the eective size of the array to making the highest index in the eective array now The largest element in this eective array index is at index so weswap elements at index and in bold The next two steps give us The last eective array has only one element and needs no sorting The entire arrayisnow sorted The algorithm for an array xwithlim elements is easy to write down for effsize lim effsize effsize find maxpos the location of the largest element in the effective array index to effsize swap elements of x at index maxpos and index effsize IMPROVING SEARCH SORTING THE DATA The implementation of the selection sort algorithm in C together with a driver program is shown in Figure Sample Session Original array Sorted array sort to sort the array and prints the sorted The driver prints the array calls selection array The co de for selection sort follows the algorithm exactly it calls get maxpos to get the index of the largest elementinanarray of a sp ecied size Once maxpos is found the element size using the temp orary variable at that index is swapp ed with the element at index eff tmp Wemay b e concerned ab out the eciency of our algorithm and its implementation as a pro gram The eciency of an algorithm dep ends on the numb er of ma jor computations involved in p erforming the algorithm The eciency of the program dep ends on that of the algorithm and the eciency of the co de implementing the algorithm Notice we included the co de for swapping array elements within the lo op in selection sort rather than calling a function to p erform this op eration A function call requires added pro cessing time in order to store argumentvalues trans fer program control and retrieve the returned value When a function call is in a lo op that may b e executed many times the extra pro cessing time may b ecome signicant Thus if the arrayto b e sorted is quite large we can improve program eciency by eliminating a function call to swap data elements Similarlywemay include the co de for get maxpos in selection sort void selectionsortint x int lim int i effsize maxpos tmp for effsize lim effsize effsize foriieffsizei maxpos xi xmaxpos i maxpos tmp xmaxpos xmaxpos xeffsize xeffsize tmp Bubble Sort An alternate way of putting the largest element at the highest index in the array uses an algorithm called bubble sort While this metho d is neither as ecient nor as straightforward as selection sort it is p opularly used to illustrate sorting We include it here as an alternate metho d Like selection sort the idea of bubble sort is to rep eatedly move the largest element to the highest index p osition of the array As in selection sort each iteration reduces the eective size of the array The two algorithms dier in how this is done Rather than search the entire eective CHAPTER SORTING AND SEARCHING File selectc This program implements selection sort include stdioh define MAX void selectionsortint x int lim int getmaxposint x int lim void printarayint x int lim main int scoresMAX printfOriginal arrayn printarayscores selectionsortscores printfSorted arrayn printarayscores Selection sort function for an array x with lim elements void selectionsortint x int lim int effsize maxpos tmp for effsize lim effsize effsize maxpos getmaxposx effsize tmp xmaxpos xmaxpos xeffsize xeffsize tmp Function returns the index of the largest element in the array x int getmaxposint x int effsize int i maxpos for i i effsize i maxpos xi xmaxpos i maxpos return maxpos Function prints an integer array of size lim void printarayint x int lim int i for i i lim i printfd xi Figure
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages36 Page
-
File Size-