C#数据结构和算法[Basic Searching Algorithms]

来源:互联网 发布:数据大小计算公式 编辑:程序博客网 时间:2024/05/22 01:32

 

 

 

Searching for data is a fundamental computer programming task and one
that has been studied for many years. This chapter looks at just one aspect of
the search problem—searching for a given value in a list (array).
There are two fundamental ways to search for data in a list: the sequential
search and the binary search. Sequential search is used when the items in the
list are in random order; binary search is used when the items are sorted in
the list.

搜索数据是计算机程序的根本任务,也是被研究了很多年的课题。

本章看一下搜索问题的某一个方面--搜索给定大小的数组。

这里有两种方法:顺序查找和二分查找。当数组里的数据是乱序时用顺序查找,排好序时用二分。

SEQUENTIAL SEARCHING
The most obvious type of search is to begin at the beginning of a set of
records and move through each record until you find the record you are
looking for or you come to the end of the records. This is called a sequential
search.
A sequential search (also called a linear search) is very easy to implement.
Start at the beginning of the array and compare each accessed array element
to the value you’re searching for. If you find a match, the search is over. If you
get to the end of the array without generating a match, then the value is not
in the array.

Here is a function that performs a sequential search:
顺序查找

是从数据集地开头挨个地搜索,直到找到你想要的。顺序查找也叫线性查找,是一种非常容易实现的算法。
从数组开头依次比较每一具元素的值是不是想要的,如果找到了,查找结束。如果数组遍历完了都找不到,那说明值不在数组里。

以下是代码实现:

 

原创粉丝点击