# Online algorithm

In computer science, an **online algorithm** is one that can process its input piece-by-piece in a serial fashion, i.e., in the order that the input is fed to the algorithm, without having the entire input available from the start. In contrast, an **offline algorithm** is given the whole problem data from the beginning and is required to output an answer which solves the problem at hand. (For example, selection sort requires that the entire list be given before it can sort it, while insertion sort doesn't.)

Because it does not know the whole input, an online algorithm is forced to make decisions that may later turn out not to be optimal, and the study of online algorithms has focused on the quality of decision-making that is possible in this setting. Competitive analysis formalizes this idea by comparing the relative performance of an online and offline algorithm for the same problem instance. For other points of view on online inputs to algorithms, see streaming algorithm (focusing on the amount of memory needed to accurately represent past inputs), dynamic algorithm (focusing on the time complexity of maintaining solutions to problems with online inputs) and Online machine learning.

A problem exemplifying the concepts of online algorithms is the Canadian Traveller Problem. The goal of this problem is to minimize the cost of reaching a target in a weighted graph where some of the edges are unreliable and may have been removed from the graph. However, that an edge has been removed (*failed*) is only revealed to *the traveller* when she/he reaches one of the edge's endpoints. The worst case for this problem is simply that all of the unreliable edges fail and the problem reduces to the usual Shortest Path Problem. An alternative analysis of the problem can be made with the help of competitive analysis. For this method of analysis, the offline algorithm knows in advance which edges will fail and the goal is to minimize the ratio between the online and offline algorithms' performance. This problem is PSPACE-complete.

在线算法只能得到一个最好的概率，没有办法去选取一定是最好的值。其实人生就是这样的一个在线算法，由于你永远不知道下一步会怎样，只能根据过去来猜测。一旦走错了，就无法再重来，你永远也没有“如果一切可以重来，我会选择......”的机会，希望我们都按照在线算法一样做出了最好的选择。智者曾说过“30岁前不要怕，30岁之后就不要悔”，一旦做出了决定就不要后悔，因为即使后悔也没有重来的机会了。

PS：说下在线算法(online algorithm)和离线(offline algorithm)算法，离线算法也就是知道了所有的输入，根据某些条件来选取最佳策略，而在线算法就是无法预知到后面的输入，只能按照目前的状况来做出下一步的最好决策，在线算法追求的是与离线算法一样的好结果。关于在线算法的详细信息可以看维基。写到后面想起了suit同学的口头禅“人一辈子就不能做错事”，呵呵。

[转自：http://www.cnblogs.com/fll/archive/2008/06/01/1211569.html]