Answer:
#include <iostream>
#include <cstring>
using namespace std;
int readInput(char *arr) {
string s;
cin >> s;
strcpy(arr, s.c_str());
return s.length();
}
void insertionSort(char *arr, int n) {
int i, key, j;
for (i = 1; i < n; 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;
}
}
void print(const char arr[],int n) {
cout << "The sorted array is : " << endl;
for(int i=0; i<n; i++) {
cout << arr[i] << " ";
}
}
int main(int argc, char** argv) {
const int SIZE=80;
char *array = new char[SIZE];
int sizeIn, sizeDet;
cout<<"input in a 1 dimensional array of characters and sorted "<<endl;
cout<<"Input the array size where size <= 20"<<endl;
cin>>sizeIn;
cout<<"Reading array"<<endl;
sizeDet = readInput(array);
if(sizeDet==sizeIn)
{
insertionSort(array,sizeIn);
print(array,sizeIn);
}
else
{
cout<<(sizeDet<sizeIn?"Input size less than specified.":
"Input size greater than specified.")<<endl;
}
return 0;
}
Explanation:
- Create a method called insertionSort to sort an array using insertion sort.
- Run a loop from starting from 1 up to n.
- Now move elements of array that are greater than key, to one position ahead of their current position .
- Create a method to display the values of the array.
- Finally display the results according to the conditions.