C语言 strcmp 快速排序

#include <stdio.h>
#include <stdlib.h>

#define MAXLINES 5000
#define MAXLEN 100

int readlines(char *lineptr[], int lines);
void _qsort(char *lineptr[], int left, int right);
void writelines(const char *lineptr[], int lines);

int main() {
  char *lineptr[MAXLINES];

  for (int i = 0; i < MAXLINES; i++) {
    lineptr[i] = (char *)malloc(MAXLEN);
  }

  int nlines;

  if ((nlines = readlines(lineptr, MAXLINES)) > 0) {
    _qsort(lineptr, 0, nlines - 1);
    writelines(lineptr, nlines);
    return 0;
  } else {
    printf("%s\n", "too much lines to read");
    return 1;
  }
}

int _getline(char *line, int len);

int readlines(char *lineptr[], int lines) {
  int i = 0;
  while (i < lines && _getline(*lineptr++, MAXLEN) > 0) {
    i++;
  }
  return i;
}

int _getline(char *line, int len) {
  char c;
  char *orig = line;
  int numc;

  while ((c = getchar()) != EOF && len-- > 0) { /* loop len times at most */
    *line++ = c; /* line always points to the next free positon in line[] */
    if (c == '\n') break;
  }

  if (len == 0) /* line[] is full */
    *(line - 1) = '\0';
  else
    *line = '\0';
  // printf("%d\n", line - orig);
  return line - orig;
}

void swap(char **, char **);
int strcmp(char *s1, char *s2);

void _qsort(char *lineptr[], int left, int right) {
  if (left >= right) return;

  swap(lineptr + left, lineptr + ((left + right) / 2));
  /* partition */
  int last = left;  // last 表示最后一个小于等于 key 的元素位置
  for (int i = left + 1; i <= right; i++) {
    if (strcmp(lineptr[left], lineptr[i]) > 0)
      swap(lineptr + (++last), lineptr + i);
  }

  /* recursion */
  swap(lineptr + left, lineptr + last);
  _qsort(lineptr, left, last - 1);
  _qsort(lineptr, last + 1, right);
}

/* 交换 *left 和 *right */
void swap(char *left[], char *right[]) {
  char *temp = *left;
  *left = *right;
  *right = temp;
}

/* return 1 if *s1 > *s2
  return -1 if *s1 < *s2
  return 0 if *s1 == *s2
*/
int strcmp(char *s1, char *s2) {
  while (*s1 == *s2 && *s1 != '\0') {
    s1++;
    s2++;
  }
  if (*s1 == *s2) return 0;
  return *s1 > *s2 ? 1 : -1;
}

void writelines(const char *lineptr[], int lines) {
  printf("========\n");
  for (int i = 0; i < lines; i++) {
    printf("%s", *lineptr++);
  }
}
posted @ 2019-10-31 15:31  HZQTS  阅读(366)  评论(0编辑  收藏  举报