0% found this document useful (0 votes)
110 views

Ds Notes V Unit C++

Uploaded by

rajalakshmicom85
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Ds Notes V Unit C++

Uploaded by

rajalakshmicom85
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Bubble Sort in C++

Sorting algorithms play a crucial role in organizing data efficiently. Bubble Sort is a simple
and easy-to-implement algorithm. In this article, we will explore Bubble Sort in C++,
understanding its working principle, implementation, time complexity, and practical
considerations.

Overview of Bubble Sort in C++:


 What is Bubble Sort?
 Bubble Sort Algorithm
 How does Bubble Sort work?
 Bubble Sort Implementation in C++
 Time Complexity Analysis
 Advantages of Bubble Sort
 Disadvantages of Bubble Sort
 Bubble Sort Applications
 FAQs
What is Bubble Sort?
Bubble Sort in C++ is a simple sorting algorithm that repeatedly compares adjacent
elements in a list and swaps them if they are in the wrong order. It continues this process until
the entire list is sorted.
Bubble Sort Algorithm
Here’s the pseudo code for the Bubble Sort algorithm in C++:

void bubbleSort(int arr[], int n)


{
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
// Swap elements arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
In the above pseudo code, arr is the input array to be sorted, and n is the length of the array.
The algorithm uses nested loops to iterate through the array, comparing adjacent elements
and swapping them if they are in the wrong order. This process is repeated until the entire
array is sorted.
advertisement
Bubble Sort Working
Here’s an example of Bubble Sort with 5 elements: 6, 4, 2, 8, 3.
Iteration 1:
 Compare 6 and 4: Swap since 4 < 6. List: 4, 6, 2, 8, 3.
 Compare 6 and 2: Swap since 2 < 6. List: 4, 2, 6, 8, 3.
 Compare 6 and 8: No swap since 6 < 8. List: 4, 2, 6, 8, 3.
 Compare 8 and 3: Swap since 3 < 8. List: 4, 2, 6, 3, 8.
Iteration 2:
 Compare 4 and 2: Swap since 2 < 4. List: 2, 4, 6, 3, 8.
 Compare 4 and 6: No swap since 4 < 6. List: 2, 4, 6, 3, 8.
 Compare 6 and 3: Swap since 3 < 6. List: 2, 4, 3, 6, 8.
Iteration 3:
 Compare 2 and 4: No swap since 2 < 4. List: 2, 4, 3, 6, 8.
 Compare 4 and 3: Swap since 3 < 4. List: 2, 3, 4, 6, 8.
Iteration 4:
 Compare 2 and 3: No swap since 2 < 3. List: 2, 3, 4, 6, 8.
The list is now sorted in ascending order. Bubble Sort iterates through the list, comparing
adjacent elements and swapping them if necessary, until the entire list is sorted.

Bubble Sort Implementation in C++


This program is successfully run on Dev-C++ using TDM-GCC 4.9.2 MinGW compiler on a
Windows system.

/*
* C++ Program to Implement Bubble Sort
*/

#include <iostream>

using namespace std;

// Sort arr[] of size n using Bubble Sort.


void BubbleSort (int arr[], int n)
{
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < n-i-1; ++j)
{
// Comparing consecutive data and switching values if value at j > j+1.
if (arr[j] > arr[j+1])
{
arr[j] = arr[j]+arr[j+1];
arr[j+1] = arr[j]-arr[j + 1];
arr[j] = arr[j]-arr[j + 1];
}
}
// Value at n-i-1 will be maximum of all the values below this index.
}
}

int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}

BubbleSort(arr, n);

// Display the sorted data.


cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];

return 0;
}
Program Explanation
1. Take input of data.
2. Call BubbleSort() function with ‘arr‘ the array of data and ‘n‘ the number of values, in
the argument list.
3. Implement Sorting algorithm using nested for loop.
4. The first loop will run on ‘i‘ from 0 to n-1.
5. The second loop will run on ‘j‘ from 0 to n-i-1.
6. Compare two consecutive values.
7. Switch the values if arr[j+1] <arr[j].
8. Return to main and display the result.
9. Exit.
Runtime Test Cases
Testcase 1: (Average Case)

Enter the number of data element to be sorted: 5


Enter element 1: 998
Enter element 2: 451
Enter element 3: 2
Enter element 4: 35
Enter element 5: 1206

Sorted Data ->2->35->451->998->1206


Testcase 2: (Best Case)
Enter the number of data element to be sorted: 5
Enter element 1: 2
Enter element 2: 332
Enter element 3: 456
Enter element 4: 1024
Enter element 5: 16565

Sorted Data ->2->332->456->1024->16565


Testcase 3: (Worst Case)
Enter the number of data element to be sorted: 5
Enter element 1: 99845
Enter element 2: 564
Enter element 3: 332
Enter element 4: 86
Enter element 5: 1

Sorted Data ->1->86->332->564->99845


Time Complexity Analysis:
Case Time Complexity Space Complexity

Best Case O(n) O(1)

Average Case O(n2) O(1)

Worst Case O(n2) O(1)


Time Complexity:
In the best case scenario, when the array is already sorted, Bubble Sort has a linear time
complexity of O(n). However, in the average and worst case scenarios, where the array is
unsorted or in reverse order, Bubble Sort has a quadratic time complexity of O(n2).
Space Complexity:
The space complexity remains constant at O(1) as Bubble Sort only requires a small amount
of additional memory for temporary variable storage.
Advantages of Bubble Sort
 Easy to understand and implement.
 Requires only a small amount of additional memory.
 Can handle partially sorted or nearly sorted lists efficiently.
 Performs sorting in-place, without requiring extra memory.
 Simple to debug and trace for identifying and fixing issues.
Disadvantages of Bubble Sort
 Bubble Sort may not be the best choice for large datasets, partially sorted lists, or
complex sorting tasks.
 It is less efficient compared to other algorithms and lacks stability in certain scenarios.
Bubble Sort Applications
 Education: Used for teaching sorting algorithms and programming concepts.
 Small datasets: Suitable for sorting small arrays or limited data.
 Testing: Helpful for testing and verifying other sorting algorithms.
 Understanding: Illustrates basic sorting principles like comparisons and swaps.
FAQs
1. What is Bubble Sort in C++?
Bubble Sort is a simple sorting algorithm in C++ that compares adjacent elements and swaps
them if they are out of order, gradually sorting the list.
2. How does Bubble Sort work in C++?
Bubble Sort works by repeatedly comparing and swapping adjacent elements until the list is
sorted.
3. What are the advantages of Bubble Sort Algorithm in C++?
Bubble Sort is easy to understand, requires minimal additional memory, and can handle
partially sorted lists.
4. What are the disadvantages of Bubble Sort Algorithm in C++?
Bubble Sort is inefficient for large datasets, not suitable for complex sorting tasks, and lacks
stability in maintaining the order of equal elements.
C++ Program to Implement Selection Sort
Problem Description
Write a C++ program to sort the given data using Selection Sort.

What is Selection Sort?


Selection sort in C++ is a simple sorting algorithm that repeatedly finds the minimum
element from the unsorted portion of an array and places it at the beginning, resulting in
a sorted array.
Selection Sort Algorithm
Here’s the pseudo code for the selection sort algorithm:

procedure selectionSort(arr: array of elements)


n = length(arr)
for i = 0 to n-2
minIndex = i
for j = i+1 to n-1
if arr[j] < arr[minIndex]
minIndex = j
swap arr[i] and arr[minIndex]
end for
end procedure

In the above pseudo code, arr represents the array to be sorted.


The selectionSort procedure iterates through the array, finding the index of the
minimum element in the unsorted portion (minIndex). It then swaps the current element
with the minimum element. This process is repeated until the entire array is sorted.
Problem Solution
1. Starting from the beginning pick one number.
2. Compare it with others one by one.
3. replace if the other number is lesser than this one.
4. Display the result.
5. Exit.

Selection Sort Working Procedure:


Initially, the array is [998, 451, 2, 35, 1206].
In each iteration:
Find the minimum element in the unsorted portion and swap it with the first unsorted
element.
Repeat until the entire array is sorted.
After the iterations:
 First: [2, 451, 998, 35, 1206]
 Second: [2, 35, 998, 451, 1206]
 Third: [2, 35, 998, 451, 1206]
 Fourth: [2, 35, 998, 1206, 451]
 Fifth: [2, 35, 451, 998, 1206]
The array is now sorted in ascending order: [2, 35, 451, 998, 1206].

Implementation of Selection Sort in C++.


This program is successfully run on Dev-C++ using TDM-GCC 4.9.2 MinGW compiler on
a Windows system.

Note: Join free Sanfoundry classes at Telegram or Youtube


/*
* Implementation of Selection Sort
*/

#include <iostream>

using namespace std;

// Sort arr[] of size n using Selection Sort.


void SelectionSort (int arr[], int n)
{
int i, j;
for (i = 0; i < n; ++i)
{
for (j = i+1; j < n; ++j)
{
// Comparing consecutive data and switching values if value at
i > j.
if (arr[i] > arr[j])
{
arr[i] = arr[i]+arr[j];
arr[j] = arr[i]-arr[j];
arr[i] = arr[i]-arr[j];
}
}
// Value at i will be minimum of all the values above this index.
}
}

int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}

SelectionSort(arr, n);

// Display the sorted data.


cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];

return 0;
}

Program Explanation
1. Take input of data.
2. Call SelectionSort() function with ‘arr’ the array of data and ‘n’ the number of values, in
the argument list.
3. Implement Sorting algorithm using nested for loop.
4. The first loop will run on ‘i’ from 0 to n-1.
5. The second loop will run on ‘j’ from i+1 to n-1.
6. Compare value at i with value at j.
7. Switch the values if arr[j+1] < arr[j].
8. Return to main and display the result.
9. Exit.

Time Complexity: O(n2)


The time complexity of the Selection Sort algorithm is O(n2) in the worst and average
case.
Space Complexity: O(1)
The space complexity is O(1) since it sorts the array in-place without requiring additional
memory allocation.
Runtime Test Cases
Testcase 1: (Average Case)
Enter the number of data element to be sorted: 5
Enter element 1: 998
Enter element 2: 451
Enter element 3: 2
Enter element 4: 35
Enter element 5: 1206

Sorted Data ->2->35->451->998->1206

Testcase 2: (Best Case)


Enter the number of data element to be sorted: 5
Enter element 1: 2
Enter element 2: 332
Enter element 3: 456
Enter element 4: 1024
Enter element 5: 16565

Sorted Data ->2->332->456->1024->16565

Testcase 3: (Worst Case)


Enter the number of data element to be sorted: 5
Enter element 1: 99845
Enter element 2: 564
Enter element 3: 332
Enter element 4: 86
Enter element 5: 1

Sorted Data ->1->86->332->564->99845

C++ Program to Implement Insertion Sort


Problem Description
Write a C++ program to sort the given data using Insertion Sort.

What is Insertion Sort?


Insertion Sort in C++ is a simple sorting algorithm that works by dividing the list into
sorted and unsorted portions. It repeatedly picks a value from the unsorted portion and
inserts it into its correct position in the sorted portion of the list.
Insertion Sort Algorithm
Here’s the pseudo code for the Insertion Sort algorithm in C++ for a list:

procedure insertionSort(list: array of elements)


n = length(list)
for i = 1 to n-1
key = list[i]
j = i - 1
while j >= 0 and list[j] > key
list[j+1] = list[j]
j = j - 1
list[j+1] = key
end for
end procedure

In the above pseudo code, list represents the array or list to be sorted.
The insertionSort procedure iterates through the list starting from the second element
(index 1). It selects each element and compares it with the elements before it, shifting
elements to the right until it finds the correct position for the selected element. This
process is repeated until the entire list is sorted in ascending order.
Problem Solution
1. This algorithm is based on sorting playing cards by picking and inserting them one by
one.
2. Here we take data element and place it in sorted list.
3. It should be placed so that list remains sorted.
4. Display the result.
5. Exit.

advertisement
Insertion Sort Working Procedure
Here’s a simple step-by-step example of how the Insertion Sort algorithm works for the
list [15, 8, 3, 11, 6]:

 Start with an unsorted list: [15, 8, 3, 11, 6].


 Step 1:Take one element at a time and insert it into its correct position in the
sorted part of the list.
 Step 2: Compare 8 with 15, insert 8 before 15: [8, 15, 3, 11, 6].
 Step 3: Compare 3 with 15 and 8, insert 3 before them: [3, 8, 15, 11, 6].
 Step 4: Compare 11 with 15, insert 11 after 8: [3, 8, 11, 15, 6].
 Step 5: Compare 6 with 15, 11, and 8, insert 6 before them: [3, 6, 8, 11, 15].
 The list is now sorted in ascending order: [3, 6, 8, 11, 15].
Implementation of Insertion Sort
This program is successfully run on Dev-C++ using TDM-GCC 4.9.2 MinGW compiler on
a Windows system.

/*
* C++ program to implement Insertion Sort using linked lists
*/

#include <iostream>
using namespace std;

// A structure to represent a node.


struct list
{
int data;
list *next;
};

// Function implementing insertion sort.


list* InsertinList(list *head, int n)
{
// Creating newnode and temp node.
list *newnode = new list;
list *temp = new list;

// Using newnode as the node to be inserted in the list.


newnode->data = n;
newnode->next = NULL;

// If head is null then assign new node to head.


if(head == NULL)
{
head = newnode;
return head;
}
else
{
temp = head;
// If newnode->data is lesser than head->data, then insert newnode
before head.
if(newnode->data < head->data)
{
newnode->next = head;
head = newnode;
return head;
}
// Traverse the list till we get value more than newnode->data.
while(temp->next != NULL)
{
if(newnode->data < (temp->next)->data)
break;
temp=temp->next;
}
// Insert newnode after temp.
newnode->next = temp->next;
temp->next = newnode;
return head;
}
}

int main()
{
int n, i, num;
// Declaring head of the linked list.
list *head = new list;
head = NULL;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>num;
// Inserting num in the list.
head = InsertinList(head, num);
}

// Display the sorted data.


cout<<"\nSorted Data ";
while(head != NULL)
{
cout<<"->"<<head->data;
head = head->next;
}
return 0;
}

Program Explanation
1. Create a head node of the list structure.
2. Take input of data and simultaneously insert it into a list using InsertinList().
3. Assign the new element as newnode.
4. If the head is null then assign newnode to head.
5. Otherwise, insert the newnode so that list remains sorted.
6. Return head to main.
7. Display the result.
8. Exit.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate


Now!
Time Complexity: O(n2)
The time complexity of the provided code is O(n2) in the worst case, where “n” is the
number of elements in the list.
Space Complexity: O(1)
The space complexity is O(1) since the additional space used is constant and does not
depend on the input size.
Runtime Test Cases
<strong>Case 1: (Average Case)</strong>

Enter the number of data element to be sorted: 5


Enter element 1: 998
Enter element 2: 451
Enter element 3: 2
Enter element 4: 35
Enter element 5: 1206

Sorted Data ->2->35->451->998->1206


<strong>Case 2: (Best Case)</strong>

Enter the number of data element to be sorted: 5


Enter element 1: 99845
Enter element 2: 564
Enter element 3: 332
Enter element 4: 86
Enter element 5: 1

Sorted Data ->1->86->332->564->99845

<strong>case 3: (Worst Case)</strong>

Enter the number of data element to be sorted: 5


Enter element 1: 2
Enter element 2: 332
Enter element 3: 456
Enter element 4: 1024
Enter element 5: 16565

Sorted Data ->2->332->456->1024->16565

C++ Program to Implement Radix Sort


This is a C++ Program to Sort the Given Data using Radix sort.

Problem Description
1. In this algorithm sorting of data is done from least significant digit to most significant
digit.
2. Here we need 10 different spaces labeled 0 to 9.
3. Assume we have ‘n’ number of inputs.
4. Let ‘d’ be the maximum number of digit the input data has.
5. The time complexity for radix sort is O(n*d).
6. Radix sort solves the problem of card sorting by sorting on the least significant digit
first.

Problem Solution
1. Get the maximum value from the input array which has ‘d’ digits.
2. Starting from least significant digit, sort the data.
3. Take this data as input for next significant digit.
4. Run the iteration till d digit.
5. Display the result.
6. Exit.

Program/Source Code
C++ program to implement Radix Sort.
This program is successfully run on Dev-C++ using TDM-GCC 4.9.2 MinGW compiler on
a Windows system.

#include <iostream>

using namespace std;


// Get maximum value from array.
int getMax(int arr[], int n)
{
int max = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}

// Count sort of arr[].


void countSort(int arr[], int n, int exp)
{
// Count[i] array will be counting the number of array values
having that 'i' digit at their (exp)th place.
int output[n], i, count[10] = {0};

// Count the number of times each digit occurred at (exp)th place


in every input.
for (i = 0; i < n; i++)
count[(arr[i] / exp) % 10]++;

// Calculating their cumulative count.


for (i = 1; i < 10; i++)
count[i] += count[i-1];

// Inserting values according to the digit '(arr[i] / exp) % 10'


fetched into count[(arr[i] / exp) % 10].
for (i = n - 1; i >= 0; i--)
{
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}

// Assigning the result to the arr pointer of main().


for (i = 0; i < n; i++)
arr[i] = output[i];
}

// Sort arr[] of size n using Radix Sort.


void radixsort(int arr[], int n)
{
int exp, m;
m = getMax(arr, n);

// Calling countSort() for digit at (exp)th place in every input.


for (exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}

int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}

radixsort(arr, n);

// Printing the sorted data.


cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
}
Program Explanation
1. Take input of data.
2. Get the maximum of input data.
3. Run the countSort() till (m/exp) > 0.
4. Sort the data on the basis of the digit at (exp)th place.
5. Assign the sorted data back to arr[] array.
6. Check the condition in step 3.
7. If false, print the sorted output.
8. Exit.

advertisement

Runtime Test Cases

Enter the number of data element to be sorted: 10


Enter element 1: 886
Enter element 2: 542
Enter element 3: 12
Enter element 4: 3
Enter element 5: 96
Enter element 6: 1125
Enter element 7: 54
Enter element 8: 129
Enter element 9: 3125
Enter element 10: 1

Sorted Data ->1->3->12->54->96->129->542->886->1125->3125


C++ Program to Implement Linear Search
What is Linear Search?
Linear search in C++ is a simple search algorithm used to find the position of a target
element in an array by sequentially checking each element until a match is found or the
end is reached.

Problem Description
Write a C++ Program that finds the position of an element in an array using a Linear
Search Algorithm.

Problem Solution
1. Create an array of numbers by taking input from the user.
2. Implement the linear search algorithm to find the position of an element in the array, if
it exists.
3. Sequentially search through the array elements, starting from the beginning.
4. If the requested element is found, return its position in the array.
5. If the element is not found, return -1 to indicate its absence in the array.

Method 1: Implement Linear Search Algorithm


In this method, we use the Linear Search Algorithm to find the position of an element in
an array. It creates a separate function for the search and calls it using an object.

Expected Input and Output


Case 1. Best Case: When the element to be searched is the first element of the array.
For example:
If the input array is {4, 6, 1, 2, 5, 3}
and the element to be searched is 4,
then the output will be Position: 1
Best Case time complexity: O(1)
advertisement

Case 2. Average Case: When the element to be searched is any random element in an
array.
For example:
If the input array is {66, -3, 31}
and the element to be searched is 31,
the output will be Position: 3
Average Case time Complexity: O(n)
Case 3. Worst Case: When the element to be searched is absent.
For example:
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate
Now!
If the input array is {1, 3, 6, 1, 9}
and the element to be searched is 10,
then the output will be "Element not present".
Worst Case time complexity: O(n)
Program/Source Code
Here is the source code of the C++ Program to find the position of an element requested
by the user using Linear Search Algorithm. The program is successfully compiled and
tested using Codeblocks gnu/gcc compiler on Windows 10. The program output is also
shown below.

/*
* C++ program to input N numbers and store them in an array.
* Do a linear search for a given key and report success
* or failure.
*/

#include <iostream>
using namespace std;
class LS
{
public:
void LinearSearch(int arr[], int value, int i, int n)
{ int found = 0;
for (i = 0; i < n ; i++)
{
if (value == arr[i] )
{
found = 1;
break;
}
}
if (found == 1)
{
cout<<"Element is present in the array at position
"<<i+1;
}
else
{
cout<<"Element is not present in the array.";
}
}
};
int main()
{ int num;
int i, keynum, found = 0;
cout<<"Enter the number of elements ";
cin>>num;
int array[num];
cout<<"Enter the elements one by one \n";
for (i = 0; i < num; i++)
{
cin>> array[i];
}
cout<<"Enter the element to be searched ";
cin>>keynum;
/* Linear search begins */
LS l1;
l1.LinearSearch(array,keynum,i,num);
return 0;
}
Program Explanation
1. Here in this program we have taken the array as an input from the user along with the
key to be searched. We have created a separate function for Linear Search.
2. When the function is called we have to run a loop n times where n is the number of
elements in an array.
3. In each iteration we are comparing the value of key with elements of array in
increasing order of array index.
4. If key is equal to one of the array elements we print the value of index at which we
found them to be equal.

Runtime Test Cases


Testcase 1: In this case, we use the linear search algorithm to find the position of the
element. The elements are entered in random order (e.g., {4, 6, 1, 2, 5, 3}), and the
element to be searched is “4”.
Enter the number of elements 6
Enter the elements one by one
4
6
1
2
5
3
Enter the element to be searched 4
Element is present in the array at position 1
Testcase 2: In this case, we use the linear search algorithm to find the position of the
element. The elements are entered in random order (e.g., {66, -3, 31}), and the element
to be searched is “31”.
Enter the number of elements 3
Enter the elements one by one
66
-3
31
Enter the element to be searched 31
Element is present in the array at position 3
Testcase 3: In this case, we use the linear search algorithm to find the position of the
element. The elements are entered in random order (e.g., {1, 3, 6, 1, 9}), and the
element to be searched is “10”.
Enter the number of elements 5
Enter the elements one by one
1
3
6
1
9
Enter the element to be searched 10
Element is not present in the array.
Method 2: Find Element in a Vector using Linear Search Algorithm
This method uses a linear search algorithm to find an element in a vector of integers.
The program takes the number of elements, input values, and the element to be
searched. It searches through the elements until the required one is found.

Program/Source Code
Here is the source code of the C++ Program to find element in a vector using Linear
Search Algorithm. The program is successfully compiled and tested using Codeblocks
gnu/gcc compiler on Windows 10. The program output is also shown below.

/*
* C++ Program to Implement Linear Search Algorithm
*/

#include <iostream>
#include <vector>

/* Function to fill Vector */


void make_vector(std::vector<int>& v)
{
int num, val;

std::cout << "Enter the number of elements in vector ";


std::cin >> num;
for (int i = 0; i < num; i++)
{
std::cin >> val;
v.push_back(val);
}
}

/* Linear Search Function */


int lin_search(std::vector<int> v, int val)
{
int key = -1;
for (int i = 0; i < v.size(); i++)
{
if (v[i] == val)
{
key = i;
break;
}
}
return key;
}

int main()
{
int key, val;
std::vector<int> v;

make_vector(v);
std::cout << "Enter the number : ";
std::cin >> val;
key = lin_search(v, val);
if (key != -1)
std::cout << "\nElement " << val
<< " is at position " << ++key;
else
std::cout << "\nElement " << val
<< " is not present";
}
Program Explanation
1. The program includes necessary header files: <iostream> for input/output and
<vector> for using vectors.
2. The make_vector() function fills a vector by taking the number of elements and the
elements themselves as input.
3. The lin_search() function performs a linear search on the vector to find a given value
and returns its position or -1 if not found.
4. In the main() function, the program creates a vector, takes input elements, and a
value to be searched from the user.
5. The program calls the lin_search() function and prints the position if the value is
found, else prints a message of its absence.
Program Output:
In this case, we use the linear search algorithm to find the position of the element in
vector. The elements are entered in random order (e.g., {2, 4, 10, 23, 32}), and the
element to be searched is “4”.

$ g++ main.cpp
$ ./a.out
Enter the number of elements in vector 5
2 4 10 23 32
Enter the number : 4
Element 4 is at position 2
C++ Program to Find a Search Sequence
using Binary Search
C++ Program to find a search sequence using Binary search.

Problem Description
1. Implement binary search to find the existence of a search sequence in an array.
2. The time complexity of Binary search is O(log(n)).

Problem Solution
1. Implement the binary search to find the first value of search sequence.
2. If it is there, then compare the remaining item sequentially.
3. Otherwise, the sequence is not there.
4. Exit.

Program/Source Code
C++ program to compare Binary and Sequential Search.
This program is successfully run on Dev-C++ using TDM-GCC 4.9.2 MinGW compiler on
a Windows system.

#include<iostream>

using namespace std;

// A function implementing Binary search on a sorted array.


int BinarySearch(int a[], int start, int end, int item, int iter)
{
int i, mid;
iter++;
// Assigning middle of the array.
mid = start + (end-start+1)/2;
// If value is less than value at start index more than end index
then item is not in the array.
if(item > a[end] || item < a[start] || mid == end)
{
cout<<"\nNot found";
return -1;
}
// Return the mid index.
else if(item == a[mid])
{
return mid;
}
// Return the start index.
else if(item == a[start])
{
return start;
}
// Return the end index.
else if(item == a[end])
{
return end;
}
// According to the item value choose the partion to proceed
further.
else if(item > a[mid])
BinarySearch(a, mid, 19, item, iter);
else
BinarySearch(a, start, mid, item, iter);
}

int main()
{
int n, i, flag=0, Bindex, a[20]={1, 9, 18, 24, 27, 35, 38, 41, 49,
53, 55, 66, 67, 72, 75, 77, 81, 89, 90, 97};
cout<<"\nEnter the number of element in the search sequence: ";
cin>>n;
int s[n];
for(i = 0; i < n; i++)
cin>>s[i];

// Get the index of the first value in the search sequence found in
data set array.
Bindex = BinarySearch(a, 0, 19, s[0], 0);

if(Bindex == -1)
{
// if return index is -1 then not found.
cout<<"\nNot found.";
return 0;
}
else
{
// If first value found then check for others sequentially.
for(i = Bindex; i < n+Bindex; i++)
if(a[i] != s[i-Bindex])
flag = 5;

if(flag == 5)
cout<<"\nNot found.";
else
cout<<"\nSequence found between index "<<Bindex<<"
and "<<Bindex+n<<".";
}

return 0;
}
Program Explanation
1. Assign the data to the array in a sorted manner.
2. Call BinarySearch() function with ‘arr’ the array of data and ‘n’ the number of values,
start and end index, iteration count and s[0] be the element to be searched in the
argument list.
3. Increment the iteration counter and compare the item value with the a[mid].
4. If item < a[mid] choose first half otherwise second half to proceed further. 5. Return
index value to main. 6. In main(), sequentially compare the remaining items of search
sequence to next items in the array. 7. Print the index range of the sequence found. 8.
Exit.

Runtime Test Cases


Case 1:
Enter the number of element in the search sequence: 3
35
38
41

Sequence found between index 5 and 8.

Case 2:
Enter the number of element in the search sequence: 3
35
38
40

Not found.

You might also like