处理数组的有效方法

时间:2013-06-04 22:21:56

标签: arrays sorting computer-science performance

假设我有以下数组。

数组1:城市列表(可能有一些与数组2相同的条目) 数组2:城市列表

我想输出以下列表:

  1. 仅限阵列1中的城市列表
  2. 仅限于阵列2的城市列表
  3. 两个阵列中的城市列表
  4. 完成1-3的最有效方法是什么?

    我正在考虑在每个数组中存储城市的名称,然后做一个foreach来比较两者。

1 个答案:

答案 0 :(得分:0)

如果您的数组已经排序,您可以并行遍历它们:

index_1 = 0 // assuming zero based indexing
index_2 = 0

repeat the follwoing loop:
if( index_0 is out of range )
  count (remaining) cities from array 2
else if( index_1 is out of range )
  count (remaining) cities from array 2
else {
a = get city from array 1 with the index_1
b = get city from array 2 with the index_2
if( a = b ) {
  increment no. of cities in both arrays
  increment both indices
}
else if( a < b )
  count cities from array 1 until city from array 2 is b, update indices
else 
  count cities from array 2 until city from array 1 is a, update indices
}
end loop

这应该在数组大小的线性时间内完成工作。

如果未对数组进行排序,则使用有效的排序算法对它们进行排序。

如果阵列很小,请不要打扰,使用嵌套循环的强力方法。