java python算法

什么是搜索算法? (What is a Search Algorithm?)

This kind of algorithm looks at the problem of re-arranging an array of items in ascending order. The two most classical examples of that is the binary search and the merge sort algorithm.

这种算法着眼于以升序重新排列项目数组的问题。 最经典的两个例子是二进制搜索和合并排序算法。

指数搜索 (Exponential Search)

Exponential Search, also known as finger search, searches for an element in a sorted array by jumping  2^i elements in every iteration, where i represents the value of loop control variable, and then verifying if the search element is present between the last jump and the current jump.

指数搜索(也称为手指搜索)通过在每次迭代中跳过2^i元素来搜索排序数组中的元素,其中i代表循环控制变量的值,然后验证在最后一次跳转之间是否存在搜索元素和当前的跳跃。

复杂性最坏的情况 (Complexity Worst Case)

O(log(N)) Often confused because of the name, the algorithm is named so not because of the time complexity. The name arises as a result of the algorithm jumping elements with steps equal to exponents of 2

O(log(N))通常由于名称而感到困惑,因此命名该算法并不是因为时间复杂。 该名称的出现是由于算法以等于2的指数步长跳跃元素

脚步 (Steps)

  1. Jump the array  2^i  elements at a time searching for the condition  Array[2^(i-1)] < valueWanted < Array[2^i] . If  2^i  is greater than the lenght of array, then set the upper bound to the length of the array.

    一次跳转数组2^i元素,以查找条件Array[2^(i-1)] < valueWanted < Array[2^i] 。 如果2^i大于数组的长度,则将数组的长度设置为上限。

  2. Do a binary search between  Array[2^(i-1)]  and  Array[2^i]

    Array[2^(i-1)]Array[2^i]之间进行二进制搜索

码 (Code)

// C++ program to find an element x in a
// sorted array using Exponential search.
#include <bits/stdc++.h>
using namespace std;int binarySearch(int arr[], int, int, int);// Returns position of first ocurrence of
// x in array
int exponentialSearch(int arr[], int n, int x)
{// If x is present at firt location itselfif (arr[0] == x)return 0;// Find range for binary search by// repeated doublingint i = 1;while (i < n && arr[i] <= x)i = i*2;//  Call binary search for the found range.return binarySearch(arr, i/2, min(i, n), x);
}// A recursive binary search function. It returns
// location of x in  given array arr[l..r] is
// present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{if (r >= l){int mid = l + (r - l)/2;// If the element is present at the middle// itselfif (arr[mid] == x)return mid;// If element is smaller than mid, then it// can only be present n left subarrayif (arr[mid] > x)return binarySearch(arr, l, mid-1, x);// Else the element can only be present// in right subarrayreturn binarySearch(arr, mid+1, r, x);}// We reach here when element is not present// in arrayreturn -1;
}int main(void)
{int arr[] = {2, 3, 4, 10, 40};int n = sizeof(arr)/ sizeof(arr[0]);int x = 10;int result = exponentialSearch(arr, n, x);(result == -1)? printf("Element is not present in array"): printf("Element is present at index %d", result);return 0;
}

搜索链接列表与数组 (Searching Linked Lists Versus Arrays)

Suppose you have to search for an element in an  unsorted  linked list and array. In that case, you need to do a linear search (remember, unsorted). Doing a linear search for an element in either data structure will be an O(n) operation.

假设您必须在未排序的链表和数组中搜索元素。 在这种情况下,您需要进行线性搜索(记住,未排序)。 对任一数据结构中的元素进行线性搜索将是O(n)操作。

Now if you have a  sorted  linked list and array, you can still search in both the data structures in O(log n) time using Binary Search. Although, it will be a bit tedious to code while using linked lists.

现在,如果您有一个排序的链表和数组,您仍然可以使用Binary Search在O(log n)时间内在两个数据结构中进行搜索。 虽然,在使用链表时进行编码有点繁琐。

Linked lists are usually preferred over arrays where insertion is a frequent operation. It's easier to insert in linked lists as only a pointer changes. But to insert in an array (the middle or beginning), you need to move all the elements after the one that you insert. Another place where you should use linked lists is where size is uncertain (you don't know the size when you are starting out), because arrays have fixed size.

通常,链表优于插入是频繁操作的数组。 只需更改指针,插入链接列表就更容易了。 但是要插入数组(中间或开头),您需要将所有元素移到要插入的元素之后。 另一个应该使用链表的地方是大小不确定(因为数组的大小是固定的,所以您不知道大小)。

Arrays do provide a few advantages over linked lists:

与链接列表相比,数组确实具有一些优势:

  1. Random access随机访问
  2. Less memory as compared to linked lists与链接列表相比,内存更少
  3. Arrays have better cache locality thus providing better performance阵列具有更好的缓存位置,从而提供更好的性能

It completely depends on the use case for whether arrays or linked lists are better.

对于数组还是链表是否更好,这完全取决于用例。

线性搜寻 (Linear Search)

Suppose you are given a list or an array of items. You are searching for a particular item. How do you do that?

假设给您一个列表或项目数组。 您正在搜索特定项目。 你是怎样做的?

Find the number 13 in the given list.

在给定列表中找到数字13。

You just look at the list and there it is!

您只要看一下清单就可以了!

Now, how do you tell a computer to find it.

现在,如何告诉计算机找到它。

A computer cannot look at more than the value at a given instant of time. So it takes one item from the array and checks if it is the same as what you are looking for.

在给定的时间,计算机所看到的值不能超过该值。 因此,它从数组中取出一项,并检查它是否与您要查找的项相同。

The first item did not match. So move onto the next one.

第一项不匹配。 因此,移至下一个。

And so on...

等等...

This is done till a match is found or until all the items have been checked.

完成此操作,直到找到匹配项或检查了所有项目。

In this algorithm, you can stop when the item is found and then there is no need to look further.

在此算法中,您可以在找到项目后停止,然后无需进一步查找。

So how long would it take to do the linear search operation? In the best case, you could get lucky and the item you are looking at maybe at the first position in the array! But in the worst case, you would have to look at each and every item before you find the item at the last place or before you realize that the item is not in the array.

那么线性搜索操作需要多长时间? 在最好的情况下,您可能会很幸运,并且您正在寻找的物品可能在阵列的第一位置! 但是在最坏的情况下,您必须先查看每个项目,然后才能找到该项目的最后一位,或者您意识到该项目不在数组中。

The complexity therefore of the linear search is O(n).

因此,线性搜索的复杂度为O(n)。

If the element to be searched presides on the the first memory block then the complexity would be O(1).

如果要搜索的元素位于第一个存储块中,则复杂度将为O(1)。

The code for a linear search function in JavaScript is shown below. This function returns the position of the item we are looking for in the array. If the item is not present in the array, the function would return null.

JavaScript中的线性搜索功能代码如下所示。 此函数返回我们要查找的项目在数组中的位置。 如果该项目不存在于数组中,则该函数将返回null。

int linearSearch(int arr[], int num)
{int len = (int)( sizeof(arr) / sizeof(arr[0]);int *a = arr;for(int i = 0; i < len; i++){if(*(a+i) == num) return i;}return -1;
}

JavaScript中的示例 (Example in JavaScript)

function linearSearch(arr, item) {// Go through all the elements of arr to look for item.for (var i = 0; i < arr.length; i++) {if (arr[i] === item) { // Found it!return i;}}// Item not found in the array.return null;
}

Ruby中的示例 (Example in Ruby)

def linear_search(target, array)counter = 0while counter < array.lengthif array[counter] == targetreturn counterelsecounter += 1endendreturn nil
end

C ++中的示例 (Example in C++)

int linear_search(int arr[],int n,int num)
{for(int i=0;i<n;i++){if(arr[i]==num)return i;}// Item not found in the arrayreturn -1;
}

Python范例 (Example in Python)

def linear_search(array, num):for index, element in enumerate(array):if element == num:return indexreturn -1

Swift中的示例 (Example in Swift)

func linearSearch(for number: Int, in array: [Int]) -> Int? {for (index, value) in array.enumerated() {if value == number { return index } // return the index of the number}return nil // the number was not found in the array
}

Java范例 (Example in Java)

int linearSearch(int[] arr, int element)
{for(int i=0;i<arr.length;i++){if(arr[i] == element)return i;}return -1;
}

PHP中的示例 (Example in PHP)

function linear_search($arr=[],$num=0)
{$n = count($arr);   for( $i=0; $i<$n; $i++){if($arr[$i] == $num)return $i;}// Item not found in the arrayreturn -1;
}$arr = array(1,3,2,8,5,7,4,0);
print("Linear search result for 2: ");
echo linear_search($arr,2);

全局线性搜索 (Global Linear Search)

What if you are searching the multiple occurrences of an element? For example you want to see how many 5’s are in an array.

如果要搜索一个元素的多次出现怎么办? 例如,您想查看数组中有5个数字。

Target = 5

目标= 5

Array = [ 1, 2, 3, 4, 5, 6, 5, 7, 8, 9, 5]

数组= [1、2、3、4、5、6、5、7、8、9、5]

This array has 3 occurances of 5s and we want to return the indexes (where they are in the array) of all of them. This is called global linear search. You will need to adjust your code to return an array of the index points at which it finds the target element. When you find an index element that matches your target, the index point (counter) will be added in the results array. If it doesn’t match the code will continue to move on to the next element in the array by adding 1 to the counter.

该数组有3个5s出现,我们想返回所有它们的索引(它们在数组中的位置)。 这称为全局线性搜索。 您将需要调整代码以返回在其找到目标元素的索引点的数组。 当找到与目标匹配的索引元素时,索引点(计数器)将添加到结果数组中。 如果不匹配,代码将通过向计数器加1继续移动到数组中的下一个元素。

def global_linear_search(target, array)counter = 0results = []while counter < array.lengthif array[counter] == targetresults << countercounter += 1elsecounter += 1endendif results.empty?return nilelsereturn resultsend
end

为什么线性搜索效率不高 (Why linear search is not efficient)

There is no doubt that linear search is simple but because it compares each element one by one, it is time consuming and hence not very efficient. If we have to find a number from say, 1000000 numbers and number is at the last location, linear search technique would become quite tedious. So, also learn about binary search, exponential search, etc. which are much more efficient than linear search.

毫无疑问,线性搜索很简单,但是由于它逐一比较每个元素,因此很耗时,因此效率不高。 如果必须从一个数字中找到一个数字,即1000000个数字并且数字位于最后一个位置,则线性搜索技术将变得非常乏味。 因此,还要了解比线性搜索有效得多的二进制搜索,指数搜索等。

二元搜寻 (Binary Search)

A binary search locates an item in a sorted array by repeatedly dividing the search interval in half.

二进制搜索通过将搜索间隔重复分成两半来找到排序数组中的项。

How do you search a name in a telephone directory?

您如何在电话簿中搜索姓名?

One way would be to start from the first page and look at each name in the phonebook till we find what we are looking for. But that would be an extremely laborious and inefficient way to search.

一种方法是从第一页开始,查看电话簿中的每个名称,直到找到所需的内容。 但这将是一种极其费力且效率低下的搜索方式。

Because we know that names in the phonebook are sorted alphabetically, we could probably work along the following steps:

因为我们知道电话簿中的名称是按字母顺序排序的,所以我们可以按照以下步骤进行操作:

  1. Open the middle page of the phonebook打开电话簿的中间页
  2. If it has the name we are looking for, we are done!如果它具有我们想要的名称,我们就完成了!
  3. Otherwise, throw away the half of the phonebook that does not contain the name否则,请丢弃电话簿中不包含姓名的一半
  4. Repeat until you find the name or there are no more pages left in the phonebook重复直到找到名称或电话簿中没有剩余页面为止

[

[

]

]

Time complexity: As we dispose off one part of the search case during every step of binary search, and perform the search operation on the other half, this results in a worst case time complexity of  O ( log2N ). The best case occurs when the element to be found is in the middle of the list. The best case time complexity is  O ( 1 ).

时间复杂度:由于我们在二分搜索的每一步中都放置了一部分搜索用例,而在另一半上执行了搜索操作,因此这导致了最差的时间复杂度O ( log2N )。 当要找到的元素在列表的中间时,将发生最佳情况。 最佳情况下时间复杂度为O ( 1 )。

Space complexity: Binary search takes constant or  O ( 1 ) space meaning that we don't do any input size related variable defining.

空间复杂度:二进制搜索占用常量或O ( 1 )空间,这意味着我们不进行任何与输入大小相关的变量定义。

for small sets linear search is better but in larger ones it is way more efficient to use binary search.

对于小集合,线性搜索更好,但在大集合中,使用二进制搜索会更有效。

In detail, how many times can you divide N by 2 until you have 1? This is essentially saying, do a binary search (half the elements) until you found it. In a formula this would be this:

详细地说,您可以将N除以2多少次,直到得到1? 本质上讲,进行二进制搜索(将元素减半),直到找到它为止。 用公式可以是:

1 = N / 2^x

Multiply by 2x:

乘以2倍:

2^x = N

Now do the log2:

现在执行log2:

log2(2^x)   = log2 N
x * log2(2) = log2 N
x * 1       = log2 N

This means you can divide log N times until you have everything divided. Which means you have to divide log N ("do the binary search step") until you found your element.

这意味着您可以将日志除以N次,直到将所有内容都除。 这意味着您必须除以log N(“执行二进制搜索步骤”),直到找到您的元素。

O ( log2N ) is such so because at every step half of the elements in the data set are gone which is justified by the base of the logarithmic function.

O ( log2N )之所以如此,是因为在每一步中,数据集中的元素的一半都消失了,这由对数函数的基数证明是正确的。

This is the binary search algorithm. It is elegant and efficient but for it to work correctly, the array must be  sorted .

这是二进制搜索算法。 它既优雅又高效,但是要使其正常工作,必须对数组进行排序

Find 5 in the given array of numbers using binary search.

使用二进制搜索在给定的数字数组中找到5。

Mark low, high and mid positions in the array.

在阵列中标记低,高和中位置。

Compare the item you are looking for with the middle element.

将您要查找的项目与中间元素进行比较。

Throw away the left half and look in the right half.

扔掉左半部分,然后看向右半部分。

Again compare with the middle element.

再次与中间元素进行比较。

Now, move to the left half.

现在,移至左半部分。

The middle element is the item we were looking for!

中间元素是我们正在寻找的物品!

The binary search algorithm takes a divide-and-conquer approach where the array is continuously divided until the item is found or until there are no more elements left for checking. Hence, this algorithm can be defined recursively to generate an elegant solution.

二进制搜索算法采用分而治之的方法,在该方法中,数组将连续划分,直到找到该项目或直到不再有要检查的元素为止。 因此,可以递归地定义该算法以生成优雅的解决方案。

The two base cases for recursion would be:

递归的两个基本情况是:

  • No more elements left in the array数组中没有剩余元素
  • Item is found找到项目

The Power of Binary Search in Data Systems (B+ trees): Binary Search Trees are very powerful because of their O(log n) search times, second to the hashmap data structure which uses a hashing key to search for data in O(1). It is important to understand how the log n run time comes from the height of a binary search tree. If each node splits into two nodes, (binary), then the depth of the tree is log n (base 2).. In order to improve this speed in Data System, we use B+ trees because they have a larger branching factor, and therefore more height. I hope this short article helps expand your mind about how binary search is used in practical systems.

数据系统中二进制搜索的力量(B +树):二进制搜索树由于其O(log n)搜索时间而非常强大,仅次于使用哈希键在O(1)中搜索数据的哈希图数据结构。 。 重要的是要了解log n运行时间如何来自二进制搜索树的高度。 如果每个节点都分成两个节点(二进制),则树的深度为log n(以2为底)。为了提高数据系统中的速度,我们使用B +树,因为它们的分支因子更大,并且因此更高的高度。 我希望这篇简短的文章可以帮助您扩大对实际系统中二进制搜索的使用方式的了解。

The code for recursive binary search is shown below:

递归二进制搜索的代码如下所示:

JavaScript实现 (JavaScript implementation)

function binarySearch(arr, item, low, high) {if (low > high) { // No more elements in the array.return null;}// Find the middle of the array.var mid = Math.ceil((low + high) / 2);if (arr[mid] === item) { // Found the item!return mid;}if (item < arr[mid]) { // Item is in the half from low to mid-1.return binarySearch(arr, item, low, mid-1);}else { // Item is in the half from mid+1 to high.return binarySearch(arr, item, mid+1, high);}
}var numbers = [1,2,3,4,5,6,7];
print(binarySearch(numbers, 5, 0, numbers.length-1));

Here is another implementation in JavaScript:

这是JavaScript的另一种实现:

function binary_search(a, v) {function search(low, high) {if (low === high) {return a[low] === v;} else {var mid = math_floor((low + high) / 2);return (v === a[mid])||(v < a[mid])? search(low, mid - 1): search(mid + 1, high);}}return search(0, array_length(a) - 1);
}

Ruby实现 (Ruby implementation)

def binary_search(target, array)sorted_array = array.sortlow = 0high = (sorted_array.length) - 1while high >= lowmiddle = (low + high) / 2if target > sorted_array[middle]low = middle + 1elsif target < sorted_array[middle]high = middle - 1elsereturn middleendendreturn nil
end

C中的例子 (Example in C)

int binarySearch(int a[], int l, int r, int x) {if (r >= l){int mid = (l + (r - l))/2;if (a[mid] == x)return mid;if (arr[mid] > x)return binarySearch(arr, l, mid-1, x);return binarySearch(arr, mid+1, r, x);}return -1;
}

Python实现 (Python implementation)

def binary_search(arr, l, r, target):if r >= l:mid = (l + (r - l))/2if arr[mid] == target:return midelif arr[mid] > target:return binary_search(arr, l, mid-1, target)else:return binary_search(arr, mid+1, r, target)else:return -1

C ++中的示例 (Example in C++)

Recursive approach!

递归的方法!

// Recursive approach in C++
int binarySearch(int arr[], int start, int end, int x)
{if (end >= start){int mid = (start + (end - start))/2;if (arr[mid] == x)return mid;if (arr[mid] > x)return binarySearch(arr, start, mid-1, x);return binarySearch(arr, mid+1, end, x);}return -1;
}

Iterative approach!

迭代的方法!

int binarySearch(int arr[], int start, int end, int x)
{while (start <= end){int mid = (start + (end - start))/2;if (arr[mid] == x)return mid;if (arr[mid] < x)start = mid + 1;elseend = mid - 1;}return -1;
}

Swift中的示例 (Example in Swift)

func binarySearch(for number: Int, in numbers: [Int]) -> Int? {var lowerBound = 0var upperBound = numbers.countwhile lowerBound < upperBound {let index = lowerBound + (upperBound - lowerBound) / 2if numbers[index] == number {return index // we found the given number at this index} else if numbers[index] < number {lowerBound = index + 1} else {upperBound = index}}return nil // the given number was not found
}

Java范例 (Example in Java)

// Iterative Approach in Java
int binarySearch(int[] arr, int start, int end, int element)
{while(start <= end){int mid = start + ( end - start ) / 2;if(arr[mid] == element)return mid;if(arr[mid] < element)start = mid+1;elseend = mid-1;}return -1;
}
// Recursive Approach in Java
int binarySearch(int[] arr, int start,int end , int element)
{if (end >= start){int mid = start + ( end - start ) / 2;if(arr[mid] ==  element)return mid;if(arr[mid] < element)return binarySearch( arr , mid + 1 , end , element );elsereturn binarySearch( arr, start, mid - 1 , element);}return -1;
}

翻译自: https://www.freecodecamp.org/news/search-algorithms-explained-with-examples-in-java-python-and-c/

java python算法

java python算法_用Java,Python和C ++示例解释的搜索算法相关推荐

  1. java 离散算法_用JAVA语言实现离散数学算法

    用JAVA语言实现离散数学算法 用JAVA语言实现离散数学算法 * 显示离散数学算法的真值表 * 提供将一个中缀合适公式的真值表输出到某一PrintStream流中的功能 * 以单个大写字母表示变量( ...

  2. java连连看算法_用 JAVA 开发游戏连连看(之三)将算法与界面结合起来

    (之三)将算法与界面结合起来 用布局和按钮来实现算法的界面 上面已经说完了算法,相信大家也迫不及待的想进入界面的设计了吧,好了,多的不说,我们开始吧. 既然我们的算法是基于二维数组的,那么我们也应该在 ...

  3. java分隔符算法_《Java数据结构和算法》栈 分隔符分配

    分隔符包括"{"."["."("."] ".")"."}",每个左分隔符需要右分 ...

  4. java 冒泡算法_关于java中的冒泡算法

    /**输入一些数字,要求按顺序输出*/importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamR ...

  5. java寻宝算法_【Java 7】今天,你寻宝了吗?

    [Java 7]今天,你寻宝了吗? 背景描述: Dmaven.multiModuleProjectDirectory system property is not set. Check $M2_HOM ...

  6. java节假日算法_基于Java代码实现判断春节、端午节、中秋节等法定节假日的方法...

    一.前言 最近工作上遇到一个问题,后端有一个定时任务,需要用JAVA每天判断法定节假日.周末放假,上班等情况,其实想单独通过逻辑什么的去判断中国法定节假日的放假情况,基本不可能,因为国家每一年的假期可 ...

  7. java 围棋算法_求java围棋提子算法

    展开全部 import java.awt.*;import java.awt.event.*; //创建棋盘的类: class ChessPad extends Panel implements Mo ...

  8. java堆算法_用Java写算法之七:堆排序

    堆是数据结构中的一种重要结构,了解了"堆"的概念和操作,可以快速掌握堆排序. 堆的概念 堆是一种特殊的完全二叉树(complete binary tree).如果一棵完全二叉树的所 ...

  9. java 线性回归算法_线性搜索或顺序搜索算法在Java中如何工作? 示例教程

    java 线性回归算法 大家好,之前,我讨论了二进制搜索算法的工作原理,并分享了在Java中实现二进制搜索的代码. 在那篇文章中,有人问我是否还有其他搜索算法? 如果数组中的元素未排序,又该如何使用它 ...

最新文章

  1. 协方差矩阵有什么意义?
  2. start.aliyun.com 正式上线!极速构建 Spring Cloud 应用
  3. 利用查找替换批处理(附完整源码),进行高效重构
  4. UVA - 10859 Placing Lampposts 放置街灯
  5. Linux Kernel 5.14 arm64异常向量表解读-中断处理解读
  6. tensorflow怎样调用gpu_tensorflow基本用法(图,会话,tensor,变量等)
  7. Windows 2003架设CA服务器 (视频)
  8. bootstrap -- 一个标签中,同时有 col-xs , col-sm , col-md , col-lg
  9. 组件切换方式(Vue.js)
  10. 沣东新城镐京遗址规划_沣东新城房价为啥这么高?
  11. 高阶篇:8.2)注塑模具讨论要点(讨模评审)
  12. 83998 连接服务器出错_Linux高性能服务器设计
  13. Python实战从入门到精通第十五讲——定义匿名或内联函数
  14. gyp安装,及breakpad上的使用方法
  15. 英尺C语言,C语言中关于英尺、英寸、厘米的换算
  16. 【游戏开发实战】使用Unity制作水果消消乐游戏教程(一):生成冰块阵列
  17. android手机电视下载软件安装失败,新买的电视无法安装第三方软件?方法汇总来了,解决99%的问题...
  18. 无限火力跳跳机器人_2021LOL无限火力机器人最强出装和天赋介绍
  19. 八月暑期福利,10本Python热门书籍免费送!
  20. 关于良率:交期延误、报废补料、不做退款都是什么情况?

热门文章

  1. [TimLinux] Python 迭代器(iterator)和生成器(generator)
  2. Android 适配(一)
  3. scrapy从安装到爬取煎蛋网图片
  4. iOS https双向配置
  5. 高数.........
  6. MongoDB 空指针引用拒绝服务漏洞
  7. 解决Windows Server2008 R2中IE开网页时弹出阻止框
  8. WPF疑难杂症之二(全屏幕窗口)
  9. Vue源码: 关于vm.$watch()内部原理
  10. springboot微服务 java b2b2c电子商务系统(一)服务的注册与发现(Eureka)