Professional Documents
Culture Documents
DIGITAL ASSIGNMENT 1
for(j=1;j<n;j++)
{
key = elements[j];
i = j-1;
while((i>=0)&&(elements[i]>key))
{
elements[i+1] = elements[i];
i = i-1;
}
elements[i+1] = key;
}
for(i=0;i<n;i++)
{
cout<<elements[i]<<" ";
}
}
OUTPUT:
CODE:
APPROACH 1
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int a[] = {2,-1,3,0,7,3};
int n = sizeof(a)/sizeof(a[0]);
LinearInsertionSort(a, n);
int n1=3;
cout << "Sorted array: \n";
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout<<"\n";
for(int i=0;i<n;i++)
{
if(a[i]==n1)
{ cout<<"Position of the element to be searched:
"<<i+1<<"\n";
break;
}
}
return 0;
}
APPROACH 2
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int a[] = {2,-1,3,0,7,3};
int n = sizeof(a)/sizeof(a[0]);
binaryInsertionSort(a, n);
int n1=3;
int c=binarySearch(a,n1,0,n);
cout<<"Position of the element to be searched: "<<c+1<<"\n";
return 0;
}
OUTPUT:
CODE:
APPROACH 1
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
int main() {
int n;
cin>>n;
char ip;
vector<char> input;
for(int i=0;i<n;i++)
{
cin>>ip;
input.push_back(ip);
}
insertionSort(input);
double time1=(double)(clock() - tStart)/CLOCKS_PER_SEC;
cout<<"Time taken is "<<time1<<endl;
APPROACH 2
#include <iostream>
#include <vector>
using namespace std;
insertionSort(input);
EXPLANATION:
Both approach have the same time complexity O(n^2) but method 1
uses extra memory to store the output sequence. So method 2 is
more efficient in terms of memory usage but the choice between
them depends on the specific use case.
CODE:
#include <iostream>
#include <ctime>
using namespace std;
int i = 0;
while (negCount > 0)
{
int temp = *(arr + i);
*(arr + i) = *(arr + negCount);
*(arr + negCount) = temp;
negCount--;
i++;
}
return arr;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
insertionSort(arr, n);
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
}
OUTPUT:
TABLE AND GRAPH:
(e) Given n points P1, P2, ..., Pn with the coordinates (x1,
y1),(x2, y2), ...,(xn, yn) respectively, write an insertion-
sort based algorithm and the corresponding code to
arrange the points in an increasing order of the distance
of the point from the origin (with (0, 0) as the coordinates.
Distance between any two points (a1, b1) and (a2, b2) is p
(a1 − a2) 2 + (b1 − b2) 2 . Input for the code is : n and the
coordinates of the n points entered with x−coordinate
first and then the y−coordinate.
CODE:
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
struct Point {
int x, y;
double distance;
};
int main() {
int n;
cout << "Enter the number of points: ";
cin >> n;
Point points[n];
insertionSort(points, n);
cout << "Points in increasing order of distance from the origin:" <<
endl;
for (int i = 0; i < n; i++) {
cout << "(" << points[i].x << ", " << points[i].y << ")" << endl;
}
return 0;
}
OUTPUT: