Write a program that sorts an array of integers into ascending order or descendi
ID: 3622315 • Letter: W
Question
Write a program that sorts an array of integers into ascending order or descending order. Use command-line arguments to pass either argument -a for ascending order or -d for descending order. [Note: This is the standard format for passing options to a program in UNIX.]
This is what I got:
#include
#include
int main(void){
int i,x;
int a[20];
srand(time(NULL));
for(i=1;i<=20;i++)
{
a[i] = 1 + rand()%1000;
printf("%d = %d ",i,a[i]);
}/* end for*/
}/* end main */
But, I don't get how to sort the array in ascending or descending order and how to use command-line argument.
Explanation / Answer
To use command line arguments, the main function should take arguments argc and argv instead of void. int main ( int argv, char * argv[]) here argv represents the number of arguments passed and argv contains the arguments. suppose you execute the program as ./a.out -a then argv is 2. That is argv[0] = a.out and argv[1] = -a Sorting: There are various algorithms for sorting such as insertion sort, merge sort , quick sort etc. You can use one of those.. This is a code for insertion sort void sort(int a[],int n) { int i,j,key; for(i=2;i0&&keyRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.