Lecture 9
Searching and Sorting
List Operations
· Search for a given item
· Sort the list
· Insert item
· Delete item
· Print List
Sequential Search
int seqSearch(const int list[], int listLength, int
searchItem)
[
int loc;
bool found=false;
loc=0;
while(loc<listLength
&& !found);
if (list[loc]==searchItem)
found=true;
else
loc++;
if (found)
return loc;
else
return)1;
Problem when item is at bottom long search
Solution is to sort items in order and then do a quicker search
Illustrate how the Bubble Sort (Compare and Swap)
algorithm would place the following numbers into order
.
Iterations
1 Largest to bottom |
2 Next larger |
3 Next larger |
4 Next larger |
89 15 15 15 15 ‡ |
15 15 15 15 ‡ |
|
|
‡ 15 89 78 78 78 ‡ |
‡ 78 78 45 45 ‡ |
|
|
‡ 78 78 89 45 45 ‡ |
‡ 45 45 78 67 ‡ |
|
|
‡ 45 45 45 89 67 ‡ |
‡ 67 67 67 78
|
|
|
‡ 67 67 67 67 89 |
89 89 89 89 |
|
|
void
bubbleSort(int list[], int
length)
{
int temp;
int iteration;
int index;
for (iteration=1;
iteration<length; iteration++)
{
for (index=0;
index<length-iteration; index++)
if
(list[index]>list[index+1])
{
temp=list[index];
list[index]=list[index=1];
list{index+1]=temp;
}
Can now do Binary Search
·
Check midpoint of list
·
Item greater or less then midpoint
·
Remove the non contained half
·
Check again midpoint of retained half
·
Proceed in this manner until found
int
binarySearch(Const int list[], int listLength, int
searchItemJJJJJJ)
{
int first=0;
int last=listLength-1;
int mid;
bool found=false;
while(first<=last
&&!found)
{
mid=(first+last)/2;
if(list[mid]==searchItem)
found=true;
else if (list[mid>searchItem)
last=mid-1;
else
first=mid+1;
}
if (found)
return mid;
else
return -1;
}