aboutsummaryrefslogtreecommitdiff
path: root/5.7.1.c
diff options
context:
space:
mode:
authorsinanmohd <pcmsinan@gmail.com>2022-06-20 09:58:02 +0530
committersinanmohd <pcmsinan@gmail.com>2022-06-20 12:48:04 +0530
commit103fbaa88a682cbeb017a57716f12a1439c32f03 (patch)
tree72ce9a7a7a193027414817377af1574cc02e3553 /5.7.1.c
parent5d8b93385decf9e618ea44f3bcca232a17ce0582 (diff)
add 5.7.1.c
Diffstat (limited to '5.7.1.c')
-rw-r--r--5.7.1.c110
1 files changed, 110 insertions, 0 deletions
diff --git a/5.7.1.c b/5.7.1.c
new file mode 100644
index 0000000..dc7403b
--- /dev/null
+++ b/5.7.1.c
@@ -0,0 +1,110 @@
+#include <stdio.h>
+#include <string.h>
+
+#define MAXLINES 5000
+#define MAXLEN 1000
+char line[MAXLINES][MAXLEN]; /* same as `char (line[MAXLEN])[MAXLINES]` */
+/* we are using a lineptr here because array `line` pointer is const like all arrays and there addreses cant be changed to sort them only values can be exchanged
+ * but copying each char back and forth would take up more resources and using a lineptr is much more efficent, here we are not actully sorting line itself
+ * but sorting pointers in lineptr to reflect the order*/
+char *lineptr[MAXLINES]; /* same as `char *(lineptr[MAXLINES])` */
+
+int readlines(char *lineptr[], int max);
+void writelines(char *lineptr[], int max);
+void my_qsort(char *lineptr[], int left, int right);
+
+int
+main(void)
+{
+ int nlines;
+
+ if ((nlines = readlines(lineptr, MAXLINES)) > 0) {
+ my_qsort(lineptr, 0, nlines);
+ writelines(lineptr, nlines);
+ return 0;
+ } else {
+ printf("Err: lines, lines everywhere\n"); /* too much lines / input too big */
+ return 1;
+ }
+ return 0;
+}
+
+int sneed_getline(char str[], int max);
+
+int
+readlines(char *lineptr[], int max)
+{
+ int len, nlines;
+
+ for (nlines = 0; (len = sneed_getline(line[nlines], MAXLEN)) > 0; nlines++) {
+ if (nlines < max) {
+ lineptr[nlines] = line[nlines];
+ }
+
+ else
+ return -1;
+ }
+
+ return nlines;
+}
+
+void
+writelines(char *lineptr[], int max)
+{
+ while (max--)
+ printf("%s\n", *lineptr++);
+}
+
+int
+sneed_getline(char str[], int max)
+{
+ char input;
+ char *str_og;
+
+ str_og = str;
+
+ --max;
+ while (--max && (input = getchar()) != EOF && input != '\n')
+ *str++ = input;
+
+ /*
+ if (input == '\n' && max)
+ *str++ = input; */
+
+ *str = '\0';
+
+ return str - str_og;
+}
+
+void swap(char *lineptr[], int to, int from);
+
+void
+my_qsort(char *lineptr[], int left, int right)
+{
+ int i, last;
+
+ if (left >= right)
+ return;
+
+ swap (lineptr, left, (left+right)/2);
+
+ last = left;
+
+ for (i = left+1; i < right; i++)
+ if (strcmp(lineptr[i], lineptr[left]) < 0)
+ swap(lineptr, i, ++last);
+
+ swap(lineptr, left, last);
+ my_qsort(lineptr, left, last - 1);
+ my_qsort(lineptr, last + 1, right);
+}
+
+void
+swap(char *lineptr[], int to, int from)
+{
+ char *temp;
+
+ temp = lineptr[to];
+ lineptr[to] = lineptr[from];
+ lineptr[from] = temp;
+}