开发者

How to arrange in alphabetical order using php

I have 2 plain text files that contain some words, like:

File 1

Aarhus
Abbott
Abbott's
Abel
Abelian
Abelson
Abelson's
Aberdeen
Aberdeen's

File 2

Acapulco
Ackerman
Acta
Adam
Adams
Adamson

This is just a sample list, the files contain more than 10000 entries and the words can be placed in any order. but one thing that makes it easy is that every single line contains only one word. Now, I know how to read these values using php one by one, but I cant understand how to merge these two files and sort them alphabetically. Can a开发者_JAVA技巧nyone suggest me how to do the sorting part?

EDIT

One more thing to mention: As you can see, there are some words containing a ' single quote. Please suggest me the answers that consider this parameter while sorting.

FURTHER EDIT

I want to eliminate duplicate values from the files. Like if there are 2 same words, then it should be taken only once.


$entries = array_merge(
             file('file_one', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES),
             file('file_two', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
           );
$entries = array_unique($entries);
sort($entries);


$lines = array_merge(file('file1.txt'), file('file2.txt'));
sort($lines);


Store both files in an array then use php sort? .-.


Since the individual files are individually sorted you can do a merge sort type of algorithm.

Here's some pseudo code:

A -> File 1
B -> File 2
C -> SortedFile
While(A and B have lines left){
  Left = NextLineFromA
  Right= NextLineFromB
  If = Left < Right // strcmp(...)
    Write Left to C
  Else
    Write Right to C
}
// Now either A or B will have lines left
Write all lines left from A||B to C

Or you can read them in, do an array_merge(), followed by a sort()

I think this would be faster because you don't have to re-sort the entire thing when you call sort()

php's sort function is a quick sort algorithm O(n log(n)) and this way is O(n)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜