-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort_array.c
More file actions
72 lines (69 loc) · 1.82 KB
/
sort_array.c
File metadata and controls
72 lines (69 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int** createArrayOfArrays(int n) {
if(n <= 0) {
return NULL;
}
int** a =(int**)malloc(sizeof(int*) * n);
if(a == NULL) {
return NULL;
}
int arrSize = 16;
for(int k = 0; k < n; ++k) {
a[k] = (int*)malloc(sizeof(int) * arrSize);
if(a[k] == NULL) {
for(int j = 0; j < k; ++j) {
free(a[j]);
}
free(a);
return NULL;
}
for(int j = 0; j < arrSize-1; ++j) {
a[k][j] = rand()%1000;
}
a[k][arrSize-1] = INT_MIN;
//bubble sort
while(1) {
int ok = 1;
for(int j = 0; j < arrSize-2; ++j) {
if((k%2 == 1 && a[k][j] > a[k][j+1]) || (k%2 == 0 && a[k][j] < a[k][j+1])) {
int tmp = a[k][j];
a[k][j] = a[k][j+1];
a[k][j+1] = tmp;
ok = 0;
}
}
if(ok) break;
}
arrSize += 4 * (rand()%2 + 1);
}
return a;
}
int main(void) {
int n = 0;
fprintf(stdout, "input number of arrays: ");
int z = fscanf(stdin, "%d", &n);
if(z == 0) {
fprintf(stderr, "incorrect input\n");
return 1;
}
int** pointers = createArrayOfArrays(n);
if(pointers == NULL) {
fprintf(stderr, "incorrect n or not enough memory\n");
return 1;
}
for(int k = 0; k < n; ++k) {
int j = 0;
while(pointers[k][j] != INT_MIN) {
fprintf(stdout, "%d ", pointers[k][j]);
++j;
}
fprintf(stdout, "\n\n");
}
for(int j = 0; j < n; ++j) {
free(pointers[j]);
}
free(pointers);
return 0;
}