
#include <stdio.h>

#include < string.h>

//字符串排序(quicksort)

//用指针数组来指向各个长短不一的字符串,借用strcmp来,

//当需要改变顺序时,只需改变指针指向即可

#define MAXLENGTH 1000

int getLine( char *line){

if(gets(line) == NULL) return 0; //char *gets(char *s)读一行到s,直接加'\0'

else return strlen(line);

}

int readLines( char *ptArray[], int maxLines){

int length, nlines;

char *p, line[MAXLENGTH];

nlines = 0;

while(length = getLine(line) > 0){

if(nlines >= maxLines || (p = ( char*)malloc( sizeof( char)*length)) == NULL)

return -1;

else{

strcpy(p, line); //char *strcpy(char *target, const char *source)

ptArray[nlines++] = p;

}

}

return nlines;

}

void writeLines( char *ptArray[], int nlines){

int i;

for(i = 0; i < nlines; i++)

puts(ptArray[i]); //int puts(const char *s)//给stdout上写一行s

}

void writeLines2( char *ptArray[], int nlines){

while(nlines-- > 0)

puts(*ptArray++); //ptArray是指针变量,相当于ptArray[0]

}

void swap( char *ptArray[], int i, int j){

char *tmp; //tmp也必须是一个指针变量,用来记录地址值

tmp = ptArray[i];

ptArray[i] = ptArray[j];

ptArray[j] = tmp;

}

void quickSort( char *ptArray[], int left, int right){

int i, last;

if(left >= right) return ;

swap(ptArray, left, (left + right)/2);

last = left;

for(i = left + 1; i <= right; i++){

if(strcmp(ptArray[i], ptArray[left]) < 0)

swap(ptArray, ++last, i);

} //int strcmp(const char *str1, const char *str2)

swap(ptArray, left, last);

quickSort(ptArray, left, last - 1);

quickSort(ptArray, last + 1, right);

}

int main( int argc, char** argv) {

int maxLines = 5;

char *ptArray[maxLines]; //每个元素ptArray[i]是一个指向char的指针

int nlines;

if((nlines = readLines(ptArray, maxLines)) >= 0){

quickSort(ptArray, 0, nlines-1);

writeLines2(ptArray, nlines);

return 0;

} else{

puts( "error: input too big to sort\n");

return 1;

}

}