问题
I am a 10th-grade student in CompSci 1. In our textbook, Practical Programming 3rd Edition, An Introduction to Computer Science Using Python 3.6, it mentions the Dutch National Flag Problem. The following is how it states the exercise, word for word:
Edsgar Dijkstra is known for his work on programming languages. He came up with a neat problem that he called the Dutch National Flag problem: given a list of strings, each of which is either "red", "green", or "blue" (each is represented several times in the list), rearrange the list so that the strings are in the order of the Dutch national flag--all the "red" strings first, then all the "green" strings, then all the "blue" strings.
Here is the python code that I wrote for the exercise:
def dutch_flag(colors: list)-> list:
"""
This function takes a list of strings of colors (red, green,
or blue),and returns a list containing them with the reds first,
the greens second, and the blues last.
"""
reds = 0
greens = 0
blues = 0
for color in colors:
color = color.lower().strip()
if color == "red":
reds += 1
elif color == "green":
greens += 1
elif color == "blue":
blues += 1
flag = []
for i in range(0, reds):
flag.append("red")
for i in range(0, greens):
flag.append("green")
for i in range(0, blues):
flag.append("blue")
return flag
My code runs in O(n) time. However, my teacher told us that this program required a sorting algorithm, which is, at best, O(n*logn). Why is my code faster?
回答1:
What you show is a counting sort. Other non-comparison options would be bucket or radix sort that also have O(n) time complexity.
It's also possible to solve this problem with a comparison based 3-way partition function that uses compares and swaps with time complexity O(n).
https://en.wikipedia.org/wiki/Dutch_national_flag_problem#Pseudocode
Normally comparison based sorts take O(n log(n)) time, but the Dutch national flag problem doesn't require this.
The 3 way partition function can be expanded to handle a larger number of colors. The first pass separates the array into 3 sub-arrays, small, middle, large, then repeats the process on each sub-array to split it into 3 sub-sub arrays and so on. 9 colors could be done in 2 passes, 1st pass separates into small, middle, large, then 2nd pass separates each sub-array into 3 parts, which is also O(n) time complexity. For n elements and k colors, the time complexity is O(n⌈log3(k)⌉), but since k is a constant, the time complexity is O(n).
来源:https://stackoverflow.com/questions/55537345/dutch-national-flag-problem-running-in-on