Write a program that will randomly generate 500 integer numbers in the range -249 to 250. Write those
numbers in a text file named “in.txt”. Now Sort (in ascending order) all the integer numbers in the file “in.txt”
using Bubble Sort. Save the sorted output into another text file named “out.txt”. (Try to write separate
function for SWAP and BUBBLE_SORT and call them from main function.)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate_arr(int a[], int size, int minVal, int maxVal);
void write_arr(char* filename, int a[], int size);
void read_arr(char* filename, int a[], int size);
void bubble_sort(int a[], int size);
void swap(int* x, int* y);
int main() {
int a[500];
generate_arr(a, 500, -249, 250);
write_arr("in.txt", a, 500);
read_arr("in.txt", a, 500);
bubble_sort(a, 500);
write_arr("out.txt", a, 500);
return 0;
}
void generate_arr(int a[], int n, int minVal, int maxVal) {
time_t t;
int i;
int range = maxVal - minVal + 1;
srand((unsigned) time(&t));
for (i=0; i<n; i++) {
a[i] = rand() % range + minVal;
}
}
void write_arr(char* filename, int a[], int n) {
FILE *f;
int i;
f = fopen(filename, "w");
if (!f) {
fprintf(stderr, "Error opening file %s\n", filename);
exit(1);
}
for (i=0; i<n; i++) {
fprintf(f, "%d\n", a[i]);
}
fclose(f);
}
void read_arr(char* filename, int a[], int n) {
FILE *f;
int i;
f = fopen(filename, "r");
if (!f) {
fprintf(stderr, "Error opening file %s\n", filename);
exit(1);
}
for (i=0; i<n; i++) {
if (fscanf(f, "%d", &a[i]) != 1) {
fprintf(stderr, "Error reading file %s\n", filename);
exit(1);
}
}
fclose(f);
}
void bubble_sort(int a[], int n) {
int i, j;
int is_inorder;
for (i=0; i<n-1; i++) {
is_inorder = 1;
for (j=1; j<n-i; j++) {
if (a[j-1] > a[j]) {
swap(&a[j-1], &a[j]);
is_inorder = 0;
}
}
if (is_inorder) {
break;
}
}
}
void swap(int* x, int* y) {
int tmp = *x;
*x = *y;
*y = tmp;
}
Comments
Leave a comment