Write a program that sort its commandline arguments of 10 nu
Write a program that sort its command-line arguments of 10 numbers, which are assumed to be integers. The first command-line argument indicate whether the sorting is in descending order (-d) or ascending order (-a), if the user enters an invalid option, the program should display an error message. Example runs of the program:
./sort –a 5 2 92 424 53 42 8 12 23 41
output: 2 5 8 12 23 41 42 53 92 424
./sort –d 5 2 92 424 53 42 8 12 23 41
output: 424 92 53 42 41 23 12 8 5 2
1) Use the selection_sort function provided for project 5. Create another function that’s similar but sorts in descending order.
2) Use string library functions to process the first command line argument.
3) Use atoi function in <stdlib.h> to convert a string to integer form.
4) Compile the program to generate the executable as sort: gcc –Wall –o sort command_sort.c
Solution
#include <stdlib>
using namespace std;
int main ( int argc, char *argv[] )
{
if ( argc != 12 ) // argc should be 12 for correct execution
{
printf(\"Invalid number of arguments\ \");
break;
}
else
{
int arr[10];
for(int i=2;i<12;i++)
{
arr[i-2]=atoi(argv[i]);
}
if(argv[1] == \"-a\")
{
selection_sort_asc(arr[10]);
}
else if(argv[1] == \"-d\")
{
selection_sort_desc(arr[10]);
}
else
{
printf(\"Invalid option\ \");
}
}
}
int selection_sort_asc(int *arr)
{
int i,j,temp;
for(i=0;i<10;i++)
for(j=i+1;j<10;j++)
{
if(*(arr+i)>*(arr+j))
{
temp=*(arr+j);
*(arr+j)=*(arr+i);
*(arr+i)=temp;
}
}
printf(\"In ascending order: \");
for(i=0;i<10;i++)
printf(\"%d \",arr[i]);
return 0;
}
int selection_sort_desc(int *arr)
{
int i,j,temp;
for(i=0;i<10;i++)
for(j=i+1;j<10;j++)
{
if(*(arr+i)>*(arr+j))
{
temp=*(arr+j);
*(arr+j)=*(arr+i);
*(arr+i)=temp;
}
}
printf(\"In descending order: \");
for(i=10;i>0;i--)
printf(\"%d \",arr[i]);
return 0;
}
