205k views
5 votes
Implement the functions specified by the prototypes. The purpose of this problem is to sort a 1-dimensional array of characters. Specify the size of the array and input the array. If the array is longer than specified, output if it is larger or smaller. Utilize the outputs supplied in main(). Example supplied in 2 test cases.STDIN554321STDOUTRead in a 1-dimensional array of characters and sort Input the array size where size ≤ 20 Now read the Array 12345*********************************************************************#include //cout,cin#include //strlen()using namespace std;//User Libraries Here//Global Constants Only, No Global Variables//Like PI, e, Gravity, or conversions//Function Prototypes Hereint read(char []);void sort(char [],int);void print(const char [],int);//Program Execution Begins Hereint main(int argc, char** argv) {//Declare all Variables Hereconst int SIZE=80;//Larger than neededchar array[SIZE]; //Character array larger than neededint sizeIn,sizeDet;//Number of characters to be read, check against length //Input the size of the array you are sortingcout<<"Read in a 1 dimensional array of characters and sort"<>sizeIn; //Now read in the array of characters and determine it's sizecout<<"Now read the Array"<

User CMIVXX
by
5.3k points

1 Answer

0 votes

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.
User Chatu
by
4.9k points