Programming in C. A simple bubble sort algorithm is attached for your reference.
ID: 3730264 • Letter: P
Question
Programming in C. A simple bubble sort algorithm is attached for your reference. Remember in your code, you have to open 2 files: an input file to read "Lab3.dat" data, and an output file to write your sorted array. The Lab3.dat file contains exactly 100 elements in random order, your task is to sort them in ascending order - smallest to greatest.
Write a program to open and read from a file (attached Lab3.dat), sort the data in ascending order (smallest to largest), and write the sorted data into an output file.
Attached simple bubble sort functions.
/* C program for implementation of Bubble sort */
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
/* A function to implement bubble sort */
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
/* Last i elements are already in place */
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
/* Main program to test above functions */
int main(void)
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
Explanation / Answer
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
/* A function to implement bubble sort */
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
/* Last i elements are already in place */
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
/* Main program to test above functions */
int main(void)
{
int arr[100];
int n = 0;
FILE* file = fopen ("Lab3.dat", "r");
int num = 0;
fscanf (file, "%d", &num);
while (n < 100)
{ arr[n] = num;
fscanf (file, "%d", &num);
n++;
}
fclose (file);
bubbleSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
FILE *out_file = fopen("output.txt", "w");
int i=0;
while(i < n){
fprintf(out_file, "%d ", arr[i]); // write to file
i++;
}
fclose (out_file);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.