Program: Write a program called mysort.c that simulates sort utility in unix and
ID: 3858164 • Letter: P
Question
Program: Write a program called mysort.c that simulates sort utility in unix and takes -r as option and a filename as arguments. Assume that the file contains only integers and may be separated by a tabspace or newline or a single space. Then read the file using the system calls and store the numbers in an array (you can assume that there are not going to be more than 10000 numbers in the file). Then sort the array using any sorting algorithm (you have used selection sort algorithm in one of the homeworks). Then display the output on the screen. If -r is provided as an option then it should sort the numbers in the reverse order. You must use a file descriptor and the file management system calls to open and read from the file.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
void selectionSort(int arr[], int n)
{
int i, j, min;
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min])
min = j;
// Swap the found minimum element with the first element
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
int main( int argc, char *args[]) {
FILE *f;
char c;
f=fopen(args[1],"rt");// open file
int array[10000];// maximum numbers
int index;
char x[20];// Maximum digits is 20
/* assumes no word exceeds length of 1023 */
while (fscanf(f, " %19s", x) == 1) {
int i = atoi (x);
// puts(x);
// printf(" %d ", i);
array[index++] = i;// store iin array
}
// printf("%d ", array[0]);
selectionSort(array, index);// call selection sort here
if (argc == 3 && strcmp(args[2], "-r") == 0)
{
int end = index - 1; // end will Point to last Element
int start = 0; // i will be pointing to first element
while (start < end) {// reverse array
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++; // increment start
end--; // decrement end
}
}
int i=0;
for (i=0;i<index;i++)
{
printf("%d ", array[i]);// print array
}
fclose(f);// close file
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.