0% found this document useful (0 votes)
2 views2 pages

Tpec-6th Lab1

The document provides implementations of various sorting algorithms, including insertion sort (both in a single and two-part format) and counting sort. It discusses the correctness of the insertion sort algorithm and its loop invariant, as well as the running time analysis that counts the number of shifts made during sorting. Additionally, it includes a frequency array used in the counting sort algorithm.

Uploaded by

osmmahajan16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Tpec-6th Lab1

The document provides implementations of various sorting algorithms, including insertion sort (both in a single and two-part format) and counting sort. It discusses the correctness of the insertion sort algorithm and its loop invariant, as well as the running time analysis that counts the number of shifts made during sorting. Additionally, it includes a frequency array used in the counting sort algorithm.

Uploaded by

osmmahajan16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Insertion Sort - Part 1

void insertionSort1(int n, vector<int> &arr) {


int num=arr[arr.size()-1];
for(int j=arr.size()-1;j>=0;j--)
{
if(num<arr[j-1])
{
arr[j]=arr[j-1];
for(auto it:arr)
cout<<it<<" ";
cout<<endl;
}
else
{
arr[j]=num;
for(auto it:arr)
cout<<it<<" ";
break;
}
}
}
========================================================
2) insertionSort2
void insertionSort2(int n, vector<int> arr) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
for(auto it:arr)
{cout<<it<<" ";
}
cout<<endl;
}
}

========================================================
3)Correctness and the Loop Invariant
void insertionsort(vector<int> arr,int n)
{
for(int i=1;i<n;i++)
{
int key=arr[i];
int j=i-1;
while(j>=0 && arr[j]>key)
{
arr[j+1]=arr[j];
j--;
}
arr[j+1]=key;
}

for(auto it:arr)
{
cout<<it<<" ";
}
========================================================
4)Running time
int runningTime(vector<int> arr) {
int shift=0;
int n=arr.size();
for(int i=1;i<n;i++)
{
int key=arr[i];
int j=i-1;
while(j>=0 && arr[j]>key)
{
arr[j+1]=arr[j];
j--;
shift++;
}
arr[j+1]=key;
}
return shift;
}
========================================================
5)counting sort
vector<int> countingSort(vector<int> arr) {
vector<int> freqarr(100);
for(auto it:arr)
{
freqarr[it]++;
}
return freqarr;}

You might also like