'Quick sort in function
Task: using the function of generating an array to a file, the function of reading an this array, and the quick sort function, sort the read array.
I wrote all the functions, it seems even the sorting is correct. I'm just not sure that elements smaller than the reference are placed to the left of it and more or equal to it are placed to the right.
The question is different - how do I initialize an array if it is already being read by the read function? Errors occur due to variable array conflicts. I tried all sorts of ways - conflict after conflict.
#include <stdio.h>
#include <stdlib.h>
#define N 10
#define A -25
#define B 25
void generation();
void read_file(int a[N]);
void qs();
int main(void) {
generation();
qs(a, 0, N-1);
}
void qs(int *a, int first, int last) {
read_file(a);
if (first < last) {
int left = first, right = last, middle = a[(left + right) / 2];
do {
while (a[left] < middle)
left++;
while (a[right] > middle)
right--;
if (left <= right) {
int tmp = a[left];
a[left] = a[right];
a[right] = tmp;
left++;
right--;
}
} while (left <= right);
qs(a, first, right);
qs(a, left, last);
}
for (int i = 0; i < N; i++) {
printf("%d ", a[i]);
}
}
void generation() {
FILE *file;
file = fopen("index.txt", "w");
srand(time(0));
for (int i = 0; i < N; i++) {
fprintf(file, "%d ", A + rand() % (A - B + 1));
}
fclose(file);
}
void read_file(int a[N]) {
FILE *file;
int i;
file = fopen("index.txt", "r");
for (i = 0; i < N; i++) {
fscanf(file, "%d ", &a[i]);
}
fclose(file);
}
Solution 1:[1]
The problem is solved. The bottom line is that the main function did not specify an array, it was necessary to initialize it and reset it in the same function, and then consider it a read_file(a) function. Thus, one array is read, it is also sorted.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ???????? ???????? |
