0% found this document useful (0 votes)
305 views26 pages

Data Structures & Algorithms: Lecture # 6

The document discusses searching and sorting algorithms. It covers sequential search, binary search, bubble sort, selection sort, insertion sort, and merge sort. Sequential search sequentially checks each element to find a match, while binary search recursively checks the middle element of a sorted list. The document provides pseudocode examples and explanations of how each algorithm works.

Uploaded by

Vicky Butt
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
305 views26 pages

Data Structures & Algorithms: Lecture # 6

The document discusses searching and sorting algorithms. It covers sequential search, binary search, bubble sort, selection sort, insertion sort, and merge sort. Sequential search sequentially checks each element to find a match, while binary search recursively checks the middle element of a sorted list. The document provides pseudocode examples and explanations of how each algorithm works.

Uploaded by

Vicky Butt
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 26

Data Structures & Algorithms

Lecture # 6
Today Topics
 Searching Algorithms
 Sequential Search
 Binary Search

 Sorting Algorithms
 Bubble Sort
 Selection Sort
 Insertion Sort
 Merge Sort
What is Searching?
 The process of finding a specific data item or record from
a list is called searching.

 Main task is efficient storage of data to facilitate fast


searching.

 Other operations like inserting and deletion are


dependent on this operation.
 For example, to delete a data item from a list, its position is first
located in the list and then the deletion operation is performed.
What is Searching?
 If specified data is found, Search is successful

 Search operation is terminates when it is successful

 If specified data is not found, search is unsuccessful

 Commonly used searching methods are:


 Sequential Search
 Binary Search
Sequential Search
 It is simple and straightforward technique to
search a specified item in an unordered list

 Specified value is searched in the list


sequentially i.e. starting from the first element
to the last element in the list in a sequence.

 When the required value is found, search


operation stops.
Sequential Search
 It is slow process

 It is used for small amounts of data

 It is not recommended for large


amount of data
Algorithm – Sequential Search
SearchItem (Item, ABC, LOC)
Find a value ITEM from an array ABC consisting of N
elements

1. start
2. Set Loc = -1
3. Repeat step-4 FOR I = 1 to N
4. If Item = ABC[I] then
Loc = I
Print “Item found at location “, Loc
End if
Algorithm – Sequential Search
5. If Loc = -1 then
Print “Item not Found”
End if
6. Exit
 void main()
{
int arr[25];
int n,item;
cout<<"How many element you want to enter in array:";
cin>>n;
for(int i=0;I <n; i++)
{
cout<<"enter the element "<<<":";
cin>>arr[i];
}
cout<<"Enter the no. you want to search";
cin>>item;
for(i=0;I < =n ; I ++)
{
if(arr[i]==item)
{
cout<<<" found at position "<<arr[i];
break;
}
}
if(i==n)
cout<<<" not found in the array“;

}
 int main(void)
{
      int array[10]
      cout<< "Enter the number you want to find (from 10 to 100)…";
      int key;
      cin>> key; 

      int flag = 0;    // set flag to off

      for(int i=0; i<10; i++)    // start to loop through the array
     {
            if (array[i] == key)   // if match is found
           {
                   flag = 1;   // turn flag on
                   break ;    // break out of for loop
            }
      }
      if (flag)    // if flag is TRUE (1)
      {
           cout<< "Your number is at subscript position " << i <<".\n";
      }
      else
      {
           cout<< "Sorry, I could not find your number in this
array."<<endl<<endl;
      }     
     return 0;
}
Algorithm – Sequential Search
ReplaceSearchItem (Value1, Value2)
Find a Value1 from an array ABC consisting of N elements
and replace with Value2

1. start
2. Set Loc = -1
3. Repeat step-4 FOR I = 1 to N
4. If Item = ABC[I] then
ABC [I] = Value2
Loc = I
Print “Item modified at location “, Loc
End if
Algorithm – Sequential Search
5. If Loc = -1 then
Print “Item not Found”
End if
6. Exit
Algorithm – Sequential Search
FindLargeValue ()
Find and print the largest value in an array ABC consisting
of N elements

1. start
2. Set Max = ABC[0]
3. Repeat step-4 FOR I = 1 to N
4. If Max < ABC[I] then
Max = ABC [I]
End if
5. Print Max
6. Exit
 (Largest Element in Array) A nonempty array
DATA with N numerical values is given. This
algorithm finds the location LOC and the value
MAX of the largest element of DATA. The variable
K is used as a counter.

 Step 1. [Initialize] Set K:= 1, LOC := 1 and


MAX:= DATA[K].
 Step 2. [increment counter]. Set K:= K + 1.
 Step 3. [Test counter] if K > N , than
write: LOC, MAX, and exit.
 Step 4. [compare and update] if MAX < DATA[K],
than,
Set LOC:=K and MAX:= DATA[K].
 Step 5. [Repeat loop]. Go to step 2.
Binary Search
 It is a more efficient technique to
search a specific item from list of
items.

 It is mostly used for relatively large


lists or table of records that are
sorted in ascending or descending
order
Binary Search
 It begins by searching the required value from the middle
of the list.

 If the required value is in the middle of the list then search


process terminates at that point.

 If the list is sorted in ascending order and the required


value is greater than the value at middle, the control goes
to the higher value to search.

 If the list is sorted in ascending order and the required


value is lesser than the value at middle, the control goes to
the lesser value to search.
Algorithm – Binary Search
BinarySearch(Item)
To find a value in an array ABC consisting of N elements
sorted in ascending order

1. Start, LOC:=NULL
2. Set BEG:= LB, END:=UB and MID:= INT((BEG+END)/2)
3. Repeat step 3 and 4 while ABC[MID] != ITEM
Algorithm – Binary Search
5. If Item < ABC [Mid] then
SET END:= MID-1.
else:
SET BEG: MID +1.
[end of if structure]
6. Set MID:= INT ((BEG+END)/2).
[end of step 2 loop]
7. If ABC[MID]=ITEM, then
SET LOC:=MID.
else:
SET LOC: NULL
8. [end of if structure]
9.exit
performance
 The advantage of a binary search over a linear search is
outstanding for large numbers.
 For an array of a million elements, binary search, O(log
N), will find the target element with a worst case of only
20 comparisons.
 Linear search, O(N), on average will take 500,000
comparisons to find the element.

 // binary search of an integer array, this search is
efficient for large arrays
  
 int main()
 {
 int a[20] = {0};
 int n, i, j, temp;
 int *beg, *end, *mid, target;
  
 printf(" enter the total integers you want to enter (make it less
then 20):\n");
 scanf("%d", &n);
 if (n >= 20) return 0;
 printf(" enter the integer array elements:\n" );
 for(i = 0; i < n; i++)
 {
 scanf("%d", &a[i]);
 }
 // sort the loaded array, a must for binary search!
 // you can apply qsort or other algorithms here
 for(i = 0; i < n-1; i++)
 {
 for(j = 0; j < n-i-1; j++)
 {
 if (a[j+1] < a[j])
 {
 temp = a[j];
 a[j] = a[j+1];
 a[j+1] = temp;
 }
 }
 }
 printf(" the sorted numbers are:");
 for(i = 0; i < n; i++)
 {
 printf("%d ", a[i]);
 }
 point to beginning and end of the array

 beg = &a[0];
 end = &a[n]; // use n = one element past the loaded
array!
 printf("\n beg points to address %d and end to %d",beg,
end); // test
  
 mid should point somewhere in the middle of these
addresses

 mid = beg += n/2;


 printf("\n mid points to address %d", mid); // test
  
 printf("\n enter the number to be searched:");
 scanf("%d",&target);
 binary search, there is an AND in the middle of while()!!!

 while((beg <= end) && (*mid != target))


 {

 // is the target in lower or upper half?

 if (target < *mid)


 {
 end = mid - 1; // new end
 n = n/2;
 mid = beg += n/2; // new middle
 }
 else
 {
 beg = mid + 1; // new beginning
 n = n/2;
 mid = beg += n/2; // new middle
 }
 }
 // did you find the target?

 if (*mid == target)
 {
 printf("\n %d found!", target);
 }
 else
 {
 printf("\n %d not found!", target);
 }
  
 getchar(); // trap enter
 getchar(); // wait
 return 0;
 }
Sorting
 The process of arranging data in a specified
order according to a given criteria is called
sorting.

 The numeric type data may be arranged either


in ascending or in descending order.

 Character type data may be arranged in


alphabetical order.
Sorting
 Sorting methods can be divided into two types based upon the
complexity of their algorithms.

 One type of sorting algorithms includes


 Bubble Sort
 Insertion Sort
 Selection Sort

 Other type consists is


 Merge Sort

 Choice of a method depends upon the type and size of data to


be sorted.

You might also like