合并两个顺序表
2009-11-06 20:52
120 查看
class Program
{
static void Main(string[] args)
{
List<int> left = new List<int>();
List<int> right = new List<int>();
for (int i = 0; i < 11; i+=2)
{
left.Add(i);
}
for (int j = 1; j < 12; j += 2)
{
right.Add(j);
}
List<int> result = Merge(left, right);
foreach(int item in result)
{
Console.Write(item + " ");
}
Console.WriteLine();
Console.ReadLine();
}
//由小到大的顺序
public static List<int> Merge(List<int> left, List<int> right)
{
int length = left.Count + right.Count;
//创建合适大小的表
List<int> result = new List<int>(length);
int leftIndex = 0;
int rightIndex = 0;
//遍历left和right,顺序比较
while (leftIndex < left.Count && rightIndex < right.Count)
{
if (left[leftIndex] < right[rightIndex])
{
result.Add(left[leftIndex]);
leftIndex++;
}
else
{
result.Add(right[rightIndex]);
rightIndex++;
}
}
//将left或者right中剩余元素加入result中
if (leftIndex < left.Count)
{
for (int i = leftIndex; i < left.Count; i++)
{
result.Add(left[i]);
}
}
if (rightIndex < right.Count)
{
for (int i = rightIndex; i < right.Count; i++)
{
result.Add(right[i]);
}
}
//返回结果
return result;
}
}
{
static void Main(string[] args)
{
List<int> left = new List<int>();
List<int> right = new List<int>();
for (int i = 0; i < 11; i+=2)
{
left.Add(i);
}
for (int j = 1; j < 12; j += 2)
{
right.Add(j);
}
List<int> result = Merge(left, right);
foreach(int item in result)
{
Console.Write(item + " ");
}
Console.WriteLine();
Console.ReadLine();
}
//由小到大的顺序
public static List<int> Merge(List<int> left, List<int> right)
{
int length = left.Count + right.Count;
//创建合适大小的表
List<int> result = new List<int>(length);
int leftIndex = 0;
int rightIndex = 0;
//遍历left和right,顺序比较
while (leftIndex < left.Count && rightIndex < right.Count)
{
if (left[leftIndex] < right[rightIndex])
{
result.Add(left[leftIndex]);
leftIndex++;
}
else
{
result.Add(right[rightIndex]);
rightIndex++;
}
}
//将left或者right中剩余元素加入result中
if (leftIndex < left.Count)
{
for (int i = leftIndex; i < left.Count; i++)
{
result.Add(left[i]);
}
}
if (rightIndex < right.Count)
{
for (int i = rightIndex; i < right.Count; i++)
{
result.Add(right[i]);
}
}
//返回结果
return result;
}
}
相关文章推荐
- 顺序表的创建,插入,删除,查找,逆序以及合并两个有序的顺序表
- 动态构建顺序表,合并两个顺序表(C语言)
- 合并两个顺序表
- 将两个顺序表的合并为顺序表
- 顺序表实现两个集合的合并
- 将两个有序顺序表合并成一个新的有序顺序表
- 两个顺序表合并成一个顺序表
- 两个有序顺序表合并
- 构造顺序表--合并两个按元素从小到大排列的顺序表
- C语言实现合并两个有序(从小到大)顺序表为一个顺序表
- 两个已排序的数组进行合并
- 数据结构学习记录-两个数组的合并
- 5-51 两个有序链表序列的合并(Java)
- 【简单算法】23.合并两个有序链表
- java实现把两个有序数组合并到一个数组的实例
- 合并两个已经排序的表
- 算法-合并两个排序的链表
- 面试 14:合并两个排序链表
- 将两个带头节点链表单链表,合并成一个新的带头节点链表……
- 合并两个排序链表