-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintsort.c
More file actions
69 lines (63 loc) · 1.71 KB
/
intsort.c
File metadata and controls
69 lines (63 loc) · 1.71 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
#include <stdio.h>
#include <stdlib.h>
#define _XOPEN_SOURCE
/* print_arr function, returns all array elements and prints a newline at the end */
void print_arr (int *ar, int len) {
for (int i = 0; i < len; i++) {
printf("%i ", ar[i]);
}
printf("\n");
}
/* sort function, very basic */
long long int intsort(int *ar, long long int len) {
long long int i, changes;
changes = 0;
for (i = 0; i < len - 1; i++) {
if (ar[i] > ar[i+1]) {
changes++;
ar[i] ^= ar[i+1];
ar[i+1] ^= ar[i];
ar[i] ^= ar[i+1];
}
}
return changes;
}
long long int get_num_ints (char *filename) {
FILE *fd;
char number[50];
long long int num = 0;
if ((fd = fopen(filename, "r")) != NULL) {
while (fgets(number, 50, fd) != NULL) {
num++;
}
fclose(fd);
}
return num;
}
void fill_arr (int *ar, char *filename) {
FILE *fd;
long long int i = 0;
char number[50];
if ((fd = fopen(filename, "r")) != NULL) {
while (fgets(number, 50, fd) != NULL) {
ar[i++] = atoi(number);
}
fclose(fd);
}
}
int main (int argc, char *argv[]) {
long long int num_ints;
long long int iterations = 1; // we ALWAYS go into the loop at least once
num_ints = get_num_ints("./randnums.txt");
printf("%lli ints in file, allocating memory ...", num_ints);
int *arr_ptr = malloc(sizeof(int) * num_ints);
printf(" DONE!\n");
fill_arr(arr_ptr, "./randnums.txt");
long long int ret = 0;
while ((ret = intsort(arr_ptr, num_ints)) != 0) {
iterations++;
}
printf("%lli iterations made\n", iterations);
free(arr_ptr);
return(EXIT_SUCCESS);
}