Examples:
input :
arr[ ] : {1,2,4,5,6}
insert number: 3
Output:
arr[ ] : {1,2,3,4,5,6 }
#include <bits/stdc++.h>
using namespace std;
int insertSorted(int arr[], int n, int key, int capacity)
{
if (n >= capacity)
return n;
int i;
for (i = n - 1; (i >= 0 && arr[i] > key); i--)
arr[i + 1] = arr[i];
arr[i + 1] = key;
return (n + 1);
}
/* Driver code */
int main()
{
int arr[20] = {1,2,4,5,6,7};
int capacity = sizeof(arr) / sizeof(arr[0]);
int n = 6;
int i, key = 3;
cout << "\nBefore Insertion: ";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
// Function call
n = insertSorted(arr, n, key, capacity);
cout << "\nAfter Insertion: ";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
Before Insertion: 1 2 4 5 6 7
After Insertion: 1 2 3 4 5 6 7
0 Comments