Ds Notes V Unit C++
Ds Notes V Unit 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.
/*
* C++ Program to Implement Bubble Sort
*/
#include <iostream>
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);
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)
#include <iostream>
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);
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.
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]:
/*
* C++ program to implement Insertion Sort using linked lists
*/
#include <iostream>
using namespace std;
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);
}
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.
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>
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);
advertisement
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.
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.
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>
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>
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.
Case 2:
Enter the number of element in the search sequence: 3
35
38
40
Not found.