Last active
August 30, 2015 16:50
-
-
Save ishankhare07/49177534335f6723b8f7 to your computer and use it in GitHub Desktop.
pointer based quick sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include "/home/ishan/Dropbox/code/c/lib/my_getline.h" | |
| #define SIZE 100 | |
| #define MAXLINES 20 | |
| char *lineptr[MAXLINES]; // store pointers to lines | |
| int readline(char**, int); | |
| void quicksort(char **, int, int); | |
| void writelines(char **, int); | |
| void swap(char **, int, int); | |
| int main() { | |
| int nlines; | |
| if((nlines = readline(lineptr, MAXLINES)) >= 0) { | |
| quicksort(lineptr, 0, nlines-1); | |
| writelines(lineptr, nlines); | |
| return 0; | |
| } else { | |
| printf("error: input too big to sort\n"); | |
| return 1; | |
| } | |
| } | |
| int readline(char **lineptr, int maxlines) { | |
| int length, nlines=0; | |
| char *p, line[SIZE]; | |
| while((length = getl(line, SIZE)) > 0) { | |
| if(nlines >= MAXLINES) { | |
| return -1; | |
| } else { | |
| p = (char*) malloc(sizeof (char) * length); | |
| strcpy(p, line); | |
| lineptr[nlines++] = p; | |
| } | |
| } | |
| return nlines; | |
| } | |
| void quicksort(char **lineptr, int left, int right) { | |
| int i, last; | |
| if(left >= right) { | |
| return; | |
| } | |
| swap(lineptr, left, (left+right)/2); | |
| last = left; | |
| for(i = left; i <= right; i++) { | |
| if(strcmp(lineptr[i], lineptr[left]) < 0) { | |
| swap(lineptr, ++last, i); | |
| } | |
| } | |
| swap(lineptr, left, last); | |
| quicksort(lineptr, left, last-1); | |
| quicksort(lineptr, last+1, right); | |
| } | |
| void swap(char *v[], int i, int j) { | |
| char *temp; | |
| temp = v[i]; | |
| v[i] = v[j]; | |
| v[j] = temp; | |
| } | |
| void writelines(char **lineptr, int nlines) { | |
| while(nlines) { | |
| printf("%s\n", *lineptr); | |
| lineptr++; | |
| nlines--; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment