Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <time.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <malloc.h>
- #include "head1.h"
- #define NMAX 20
- int read_array(const char* name, double *a, int maxn)
- {
- int i;
- FILE* fp;
- if(!(fp = (fopen(name,"r"))))return -1;
- for(i = 0; i < maxn; i++)
- {
- if(fscanf(fp, "%lf", a + i)!= 1)
- {
- if(feof(fp))
- {
- fclose(fp);
- return -2;
- }
- else{
- fclose(fp); return i;
- }
- }
- }
- fclose(fp);
- return i;
- }
- void init_array(double *a, int n, int key)
- {
- int i;
- srand(key);
- for(i = 0; i < n; i++)
- a[i] = rand();
- }
- void print_array(double *a, int n)
- {
- int i;
- int m = (n > NMAX? NMAX:n);
- for(i = 0; i < m; i++)
- printf("%lf ", a[i]);
- }
- void merge(double *a, double *c, int left, int right)
- {
- int i = 0;
- int j = 0;
- int middle = (left + right) / 2;
- c = a;
- while((i + j) < (right - left)){
- if(a[left + i] <= a[middle + j]){
- c[left + i + j] = a[left + i];
- if(i < (middle - left)){i++;}
- }else{
- c[left + j + i] = a[middle + j];
- if(j < (right - middle)){j++;}
- }
- }
- a = c;
- }
- void sort(double *a, double* c, int n)
- {
- int k = 2;
- int j;
- while((1 >> k) < n)
- {
- for(j = 0; j < (n / k); j++)
- {
- merge(a, c, k * j, k * (j + 1));
- }
- if (((n / k) * k) != n)
- {
- merge(a, c, k * (j + 1), n - 1);
- }
- k++;
- }
- }
- int main(void)
- {
- int n, key;
- double *a, t, *c;
- int res;
- const char* name = "A.txt";
- printf("Input n and key\n");
- if(scanf("%d%d", &n, &key)!= 2)
- {
- printf("Cannot read");
- return 1;
- }
- if(!(a = (double*)malloc(n*sizeof(double))))
- {
- printf("Not enough memory!\n");
- return 2;
- }
- if (key == 0)
- {
- res = read_array(name, a, n);
- if (res < 0)
- {
- switch (res)
- {
- case (-1):
- {
- printf("Cannot open %s\n", name);
- break;
- }
- case (-2):
- {
- printf("Cannot read %s\n", name);
- break;
- }
- default:
- {
- printf("Unknown error %d in %s\n", res,name);
- }
- }
- free(a); return 3;
- }
- if (res == 0)
- {
- printf("The file %s is empty\n", name);
- return 0;
- }
- else n = res;}
- else init_array(a, n, key);
- c = (double*)malloc(n*sizeof(double));
- sort(a, c, n);
- print_array(a, n);
- free(a);
- free(c);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement