Insertion Sort Algorithm: Problem Exercises Problem 1 Pseudocode
Insertion Sort Algorithm: Problem Exercises Problem 1 Pseudocode
Problem Exercises
Problem 1
Pseudocode:
Q1:
1. Start.
2. Declare swap and bubble short two function
3. We take a condition of bool in which is true then simple print variable
4. Otherwise it swaps until condition true
5. Declare main and take a random value using for loop
6. Then call function whish sort the random value in ascending order and print as
ascending order
7. End
#include <iostream>
#include <string>
using namespace std;
int main()
{
int arr[] = {4,2,5,1,6,0,7,8};
cout<<"Before sort"<<endl;
for(int i = 0; i < 8; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl<<"After sort"<<endl;
bubble_sort(arr, 8);
It improves the function as it stops as soon as the flag is false for an iteration.
Problem 2
Time complexity for standard insertion sort is O(n2) because it runs on two loops, Time complexity for
double insertion sort should be O(n) because it runs on a single loop. It is faster than standard as it
completes its sorting at half the time taken.
1. Start
2. Make a function
swap(nums[m], nums[m+1]);
m--;
if(m == 0)
m = l-1;}}}}
3. End
Problem 3
The contents of the array will remain the same as the array is already in order.
Problem 4
In normal insertion sort, it takes O(n 2) comparisons(at nth iteration) in the worst case. We can reduce it to
O(log n) by using binary search.
By adding binary search to the already sorted elements we can reduce the amount of checks needed to
find the next element to swap. Since the left side elements are sorted we can use binary search on them.
Problem 5
1. Star
2. Take a function
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}
3. end
Using a minimum index we can set the boundary for already sorted elements so
they don't need to be checked again.