Data structure algorithm induction

Recursive thinking

For example: Fibonacci sequence: 1 1 2 3 5 8 13 ……Requirement: Find the value corresponding to the specified position N.
Go to the blog settings page, choose a code piece highlighting style you like, the same highlighting is shown below 代码片.

//递推思想
//需求 1 1 2 3 5 8 13 ...... 求出指定位置N对应的值是多少

$f[1] = 1;
$f[2] = 1;
//列出数组元素
$des = 15;
for($i = 3;$i <= $des;$i++){
    
    
    $f[$i] = $f[$i-1] + $f[$i-2];
}

echo '<pre>';
print_r($f);
//建立函数寻找
function my_recursive($des){
    
    
    if($des == 1 || $des == 2) return 1;

    //开始计算
    $f[1] = 1;
    $f[2] = 1;

    for($i = 3;$i <= $des;$i++){
    
    
        $f[$i] = $f[$i-1] + $f[$i-2];
    }
    return $f[$des];
}

echo '第15个元素的值为:' . my_recursive(15);

Effect picture:
Insert picture description here

Recursive thinking

The important points of recursive thinking: recursive point and recursive exit .
Recursion point : It is found that the current problem can have a function to solve the current problem, to solve the problem of a smaller scale than the current one. For example: F(N) = F(N-1)+F(N-2);
Recursive exit : When the current problem is solved, the (must have) optimal sub-problem has been reached, and the function cannot be called again.
Essence : space for time

//递归思想
//用递归的思想求斐波那契数列
//递归一定有函数

function recursion($n){
    
    
    //递归出口
    if($n ==1 || $n == 2) return 1;

    //递归点:求N得值,与求N-1的值一模一样,只是N-1的规模比N小
    return recursion($n-1) + recursion($n-2);
}

//调用
echo recursion(15);

Bubble Sort

Bubble Sort (Bubble Sort) is a relatively simple sorting algorithm in the field of computer science. It repeatedly visited the sequence to be sorted, compared two elements at a time, and exchanged them if they were in the wrong order. The work of visiting the sequence is repeated until there is no need to exchange, that is, the sequence has been sorted.

Bubbling ideas:
1. Compare adjacent elements, if the first one is not as big as the second, swap them two
2. Do the same work for each adjacent element, from the first pair at the beginning to the last one at the end Correct. At this point, the last element should be the largest number.
3. Repeat the above steps for all elements, except for the last one.
4. Continue to repeat the above steps for fewer and fewer elements each time until there is no pair of numbers to compare.

//数组排序算法:冒泡排序

$arr = array(1,4,2,9,7,5,8);
$a = 0;

//2、想办法让下面可以每次找出最大的代码重复执行
for($i = 0; $i < count($arr)-1; $i++){
    
    
//1、想办法将最大的值放到右边
    for($j = 0; $j < count($arr)-1-$i; $j++){
    
    
        if($arr[$j] > $arr[$j+1]){
    
    
            $temp = $arr[$j];
            $arr[$j] = $arr[$j+1];
            $arr[$j+1] = $temp;
        }
        $a++;
    }
}


echo '<pre>';
print_r($arr);
echo '计算次数:' . $a;

Effect picture:
Insert picture description here

Select sort

Selection sort (Selection sort) is a simple and intuitive sorting algorithm. Its working principle is to select the smallest (largest) element from the data elements to be sorted each time and store it at the beginning of the sequence until all sorted data elements are arranged. Selection sorting is the most unstable sorting method (such as the sequence [5,5,3]) swapping the first 5 and 3 for the first time, causing the first 5 to move to the second 5.
Ideas:
1. Assumption The first element is the smallest element, write down the subscript
2. Look for the remaining elements on the right, if there is a smaller one, rewrite the latest subscript
3. If there is a new smallest one, swap the two elements
4. Go Repeat the above steps to the right until the element itself is the last

//数组排序算法:选择排序

$arr = array(1,5,2,9,6,3,4);

//1、确定要交换多少次,一次只能找到一个最小的,需要找到数组长度对应的次数
for($i = 0,$len = count($arr); $i < $len; $i++){
    
    
    //2、假设当前第一次已经排好序了
    $min = $i;
    //3、拿该最小的取比较剩余的其他
    for($j = $i+1; $j < $len; $j++){
    
    
        //4、比较当前最小值和指定值
        if($arr[$j] < $arr[$min]){
    
    
            //说明当前指定的min不合适
            $min = $j;
        }
    }

    //5、交换最小值的小标
    if($min != $i){
    
    
        $temp = $arr[$i];
        $arr[$i] = $arr[$min];
        $arr[$min] = $temp;
    }
}
echo '<pre>';
print_r($arr);

Effect picture:
Insert picture description here

Insertion sort

Insertion sort is to insert a piece of data into the ordered data that has been sorted.
Ideas:
1. Determine that the first element has been sorted
2. Take out the second element as the data to be inserted
3. Start the comparison with the rightmost of the sorted array
4. If the latter is smaller than the previous one: Explain that the array element that has been ordered before is not in the right position (move one bit backward), and then fill in the new element.
5. Repeat the previous steps: until the current element is inserted in the right position

//php数组排序:插入排序
$arr = array(4,2,6,8,9,5);

//1、确定要插入的次数(同时假设第一个位置是对的)
for($i = 1, $len = count($arr); $i < $len; $i++){
    
    
    //2、取出当前要插入的元素值
    $temp = $arr[$i];

    //标记:默认说明当前要插入的数组位置是对的
    $change = false;
    //3、让该数据与前面已经排好序的数组元素重复比较,直到位置正确
    for($j = $i - 1;$j >= 0; $j--){
    
    
        //比较
        if($arr[$j] > $temp){
    
    
            $arr[$j+1] = $arr[$j];
            //$arr[$j] = $temp;

            //说明前面顺序位置有不合适的位置
            $change = true;
        }else{
    
    
            //说明当前带插入元素,比前面大,位置正确
            break;
        }
    }
    //判断位置是否有变动
    if($change){
    
    
        //有数据移动:占错位置了
        $arr[$j+1] = $temp;
    }
}

echo '<pre>';
print_r($arr);

Quick sort

Quick sort (Quick sort) is an improvement to bubble sort. Split the data to be sorted into two independent parts by sorting, one part of which all data is smaller than the other part, and then according to this method to quickly sort the two parts, the whole sorting process can be recursively, so as to achieve the whole The data becomes an ordered sequence.
Algorithm idea:
1. Select an element from the array (usually the first one) as a reference
2. Define two arrays and compare the remaining elements in the target array with the reference element one by one; put an array for the smaller one, and an array for the larger one
3. 、 After the execution, the order of the front and back arrays is uncertain, but their position is determined.
4. Repeat the resulting small array from 1 to 3.
5. Backtrack the smallest array (1 element)

//php数组排序:快速排序

$arr = array(5,6,3,4,9,2,7,8);

//快速排序
function quick_sort($arr){
    
    
    //递归出口
    $len = count($arr);
    if($len <= 1) return $arr;

    //取出某个元素。然后将剩余的数组元素,分散到两个不同的数组中
    $left = $right = array();

    for($i = 1; $i < $len; $i++){
    
    
        //第一个元素作为比较元素
        //比较:小的放left,大的放right中
        if($arr[$i] < $arr[0]){
    
    
            $left[] = $arr[$i];
        }else{
    
    
            $right[] = $arr[$i];
        }
    }

    //left和right没有排好序:递归点
    $left = quick_sort($left);
    $right = quick_sort($right);

    //合并三个“数组”
    return array_merge($left,(array)$arr[0],$right);

}

echo '<pre>';
print_r(quick_sort($arr));

Merge sort

Merge sort
Merge sort (merge sort) is an effective sorting algorithm based on the merge operation. This algorithm is a typical application of divide and conquer. Combine the existing ordered subsequences to obtain a completely ordered sequence; that is, first use each subsequence to order, and then make the subsequence ends in order, and then merge the two ordered lists into one ordered list, which becomes two Road merged.

The merge sort algorithm is:
1.
Divide the array into two arrays 2. Repeat step 1 to split the array into two smallest units
3. Apply for space to make the size of the two sorted sequences to the sum, and this space is used to store the merge After the sequence
4. Set two pointers, the initial positions are the starting positions of the two sorted sequences respectively.
5. Compare the elements pointed to by the two pointers, select relatively small elements and put them into the merge space, and move the pointers to Next position
6. Repeat step 3 until a pointer exceeds the end of the sequence
7. Copy all remaining elements of the other sequence directly and merge the end of the sequence

//PHP数组算法:归并排序

/**二路归并*/
$arr1 = array(1,3,5);
$arr2 = array(2,4,6);

//取出数组用于归并空间
$arr3 = array();

while(count($arr1) && count($arr2)){
    
    
    //如果数组中都还有数据,则循环
    $arr3[] = $arr1[0] < $arr2[0] ? array_shift($arr1) :array_shift($arr2);
}
//print_r(array_merge($arr3,$arr1,$arr2));

/**归并排序*/
$arr = array(4,7,2,1,5,9,3,5,6);

//归并排序函数
function merge_sort($arr){
    
    
    //递归出口
    $len = count($arr);
    if($len <= 1) return $arr;

    //拆分
    $middle = floor($len/2);
    $left = array_slice($arr,0,$middle);
    $right = array_slice($arr,$middle);

    //递归出口
    $left = merge_sort($left);
    $right = merge_sort($right);

    //假设左边和右边都已经排序好了
    $arr3 = array();
    while(count($left) && count($right)){
    
    
        //只要$left和$right都还有元素
        $arr3[] = $left[0] < $right[0] ? array_shift($left) :array_shift($right);
    }
    return array_merge($arr3,$left,$right);
}
echo '<pre>';
$t1 = microtime(true);
print_r(merge_sort($arr));
$t2 = microtime(true);
echo '耗时' . round($t2 - $t1,3).;

Search algorithm

Search algorithm meaning:
Search is to find a specific information element in a large amount of information. In computer applications, search is a common basic operation. Search algorithm refers to the corresponding code knot in the search process. It is to quickly locate the desired element in a large array.

Sequential search algorithm :
Sequential search is also called linear search. It starts from a section of the linear table of data structure and scans sequentially. It compares the scanned node key with the given k value in turn. If they are equal, the search is successful. Find a node with a keyword equal to k, indicating that the search failed

Binary search algorithm :
Binary search requires that the nodes in the linear table are arranged in ascending or descending order of keywords, and the given value k is used to compare the keywords of the intermediate node. The intermediate node divides the linear table into two sub-tables, if they are equal The search is successful; if they are not equal, determine which sub-table to look for next according to the comparison result of k and the intermediate node key, and proceed recursively until the search or search ends and there is no such node in the table.

Binary search code:

//二分法查找
$arr = array(1,2,3,4,5,6,7);
$res = 100;

function check_break($arr,$res){
    
    
    //1、得到数组边界
    $right = count($arr)-1;
    $left = 0;

    //2、循环匹配
    while($right >= $left){
    
    
        //3、得到中间位置
        $middle = floor(($right + $left)/2);

        //4、匹配数据
        if($arr[$middle] == $res){
    
    
            return $middle + 1;
        }

        //没有找到
        if($arr[$middle] < $res){
    
    
            //值在右边
            $left = $middle + 1 ;
        }else{
    
    
            //值在左边
            $right  = $middle - 1;
        }
    }
    return false;
}

echo '<pre>';
var_dump(check_break($arr,$res));

If it helps you, just like it!

Guess you like

Origin blog.csdn.net/weixin_43477545/article/details/106826943