using C++ to sort user input. for example, user enter 25numbers and sort them from small to big or big to small, cout thesamllest, the middle one on the sort list ( in 25 number would bethe 13th number) and the biggest?

Respuesta :

Answer:

C++ code:

#include<iostream>

using namespace std;

void sort(int al[30], int l)

{

//we use insertion sort to sort the array.

int p,q,k;

for(q=1;q<l;q++)   //starting from the 2nd item of the array.

{

 k= al[q];   //taking qth item as key value.

 p=q-1;

 while(p>=0 && al[p]>k)

 {

  al[p+1]=al[p]; //all items those are greaer than al[q] are shifted //to right.

  p=p-1;

 }

 al[p+1]=k;

}

}

int main()

{

int p,l, arrl[30];

cout<<"Enter the number of items in your array: ";

cin>>l;

cout<<endl;

 

cout<<"Enter your "<<l<<" items"<<endl;

for(p=0;p<l;p++)

{

 cin>>arrl[p];

}

 

sort(arrl, l);  //call function sort() to sort the array.

 

cout<<"The array after sorting: ";

for(p=0;p<l;p++)

{

 cout<<arrl[p]<<" ";

}

cout<<endl;

 

cout<<"The smallest item is: ";

cout<<arrl[0]<<endl;

 

cout<<"The middle item is: ";

cout<<arrl[l/2]<<endl;

 

cout<<"The biggest item is: ";

cout<<arrl[l-1]<<endl;

}

Output is given as image.

Ver imagen SerenaBochenek
ACCESS MORE