Write An Algorithm and C++ Implementation For The Following: A) Insertion Sort Ans: Algorithm
Write An Algorithm and C++ Implementation For The Following: A) Insertion Sort Ans: Algorithm
a) Insertion sort
ANS:
Algorithm;
Start
1. Declare variables i,key,j;
2. Loop: 1 to n-1 // outer loop
2.1 key = a[i]
2.2 j=j-1
2.3 loop(j>=0&&arr[j]>key) //inner loop
2.3.1 arr[j+1]= arr[j]
2.3.2 j=j-1
end loop // inner loop
2.4 arr[j+1]=key
end loop //outer loop
Stop
Code;
#include <iostream>
using namespace std;
void insertionSort(int arr[])
{
int key, j=0;
for (int i = 1; i < 5; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main()
{
int arr[5];
cout<<"Enter 5 integers in any order"<<endl;
for (int i=0 ;i<5;i++)
{
cin>>arr[i];
}
cout << "Before Sorting :"<<endl;
for (int i=0 ;i<5;i++)
{
cout<<arr[i]<<" ";
}
insertionSort(arr);
cout<< endl<<"After Sorting :"<<endl;
for (int i=0 ;i<5;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
b) Selection sort
ANS;
Algorithm;
Start
for i := 0 to size-1 do
Min := i;
for j:= i+1 to size-1 do
if array[j] < array[Min] then
Min := j
done
swap array[i] with array[Min].
done
Stop
Code;
#include<iostream>
using namespace std;
void swapping(int &a, int &b) {
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << "\n";
}
void selectionSort(int *array, int size) {
int i, j, min;
for(i = 0; i<size-1; i++) {
min = i;
for(j = i+1; j<size; j++)
if(array[j] < array[min])
min = j;
swap(array[i], array[min]);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter elements:\n";
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: \n";
display(arr, n);
selectionSort(arr, n);
cout << "Array after Sorting: \n";
display(arr, n);
}
c) Exchange sort
ANS:
Algorithm
Start
for i := 0 to size-1 do
for j:= i+1 to size-1 do
if array[j] < array[Min] then
swap array[i] with array[j];
done
done
End
Code
#include<iostream>
using namespace std;
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << "\n";
}
void selectionSort(int *array, int size) {
int i, j, temp;
for(i = 0; i<size-1; i++) {
for(j = i+1; j<size; j++){
if(array[j] < array[i]){
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter elements:\n";
for(int i = 0; i<n; i++) {
Labsheet.pdf
cin >> arr[i];
}
cout << "Array before Sorting: \n";
display(arr, n);
selectionSort(arr, n);
cout << "Array after Sorting: \n";
display(arr, n);
}