dsa lab 3
dsa lab 3
Class: BSCS- 4C
DSA LAB 04
Sol:
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n)
{
for (int i=1; i<n; i++) //index 1
{
int key=arr[i];
int j=i-1; //index 0
while (j>=0 && arr[j]>key)
{
arr[j+1]=arr[j];
j--;
}
arr[j+1]=key;
}
}
int main()
{
int n;
cout<<"Enter the number of elements: ";
cin>>n;
int arr[n];
cout<<"Enter the elements: ";
for (int i=0; i<n; i++)
{
cin>>arr[i];
}
insertionSort(arr, n);
cout<<"Your Sorted array is: ";
for (int i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
Output:
Task 02: Write a C++ program to implement binary search.
Sol:
#include <iostream>
using namespace std;
int main()
{
int arr[]={1,2,3,4,5,7};
int n=6;
int data=3;
int l=0;
int r= n-1;
while(l<=r)
{
int mid= (l+r)/2;
if (arr[mid]== data)
{
cout<<"Element found at "<<mid<<endl;
break;
}
else if(arr[mid]<data)
{
l=mid+1;
cout<<"Element found at "<<l<<endl;
break;
}
else
{
r=mid-1;
cout<<"Element found at "<<r<<endl;
break;
}
}
return 0;
}
Output:
Task 03: Write a C++ program to implement linear search.
Sol:
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the number of elements in the array: ";
cin>>n;
int arr[n];
cout<<"Enter the elements you want to enter in the array: ";
for (int i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Entered Array is: ";
for (int i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
int find;
cout<<"Enter the element you want to find in the array: ";
cin>>find;
bool found=false;
for(int i=0; i<n; i++)
{
if (arr[i]==find)
{
cout<<"Your element "<<find<<" is found at "<<i<<" index ";
found= true;
break;
}
}
if (!found)
{
cout<<"Element not found. "<<endl;
found= false;
}
return 0;
}
Output: