"Turn" data structure and algorithm (bottom)

Source: Internet
Author: User
Tags sorts

This article is a common data structure and algorithm collation summary of the next, the previous article is mainly on the common information structures to summarize, this article is mainly to summarize some common algorithm related content, the article if there are errors, welcome to point out.

一、概述二、查找算法三、排序算法四、其它算法五、常见算法题六、总结
I. Overview

Previously saw such a sentence, language is only a tool, algorithm is the soul of program design. Indeed, the position of the algorithm in computer science is really important, in many large companies in the written interview, the degree of algorithmic mastery of the survey has occupied a large part. Whether it's for an interview or an increase in your own programming skills, it's necessary to take the time to study common algorithms. Here is my own study of the algorithm this part of the summary.


Introduction to Algorithms

The algorithm refers to the accurate and complete description of the solution, is a series of clear instructions to solve the problem, the algorithm represents a systematic approach to describe the problem-solving strategy mechanism. For the solution of the same problem, there may be different algorithms, in order to measure the merits and demerits of an algorithm, the space complexity and time complexity of the two concepts are proposed.

Complexity of Time

In general, the number of executions of basic operations in the algorithm is a function f (n) of the problem size n, the time metric of the algorithm is denoted by T (n) = O (f (n) ), which indicates that the growth rate of the algorithm execution time and the growth rate of f (n) are the same with the increase of the problem size n It is called the asymptotic time complexity of the algorithm, which is referred to as time complexity. There is a need to focus on understanding this growth rate.

举个例子,看下面3个代码:1、{++x;}2、for(i = 1; i <= n; i++) { ++x; }3、for(j = 1; j <= n; j++)         for(j = 1; j <= n; j++)              { ++x; }上述含有 ++x 操作的语句的频度分别为1 、n 、n^2,假设问题的规模扩大了n倍,3个代码的增长率分别是1 、n 、n^2它们的时间复杂度分别为O(1)、O(n )、O(n^2)

Complexity of space

Spatial complexity is a measure of the amount of storage space that is temporarily occupied by an algorithm while it is running, and is recorded as S (n) =o (f (n)). The advantages and disadvantages of an algorithm are mainly measured from the execution time of the algorithm and the storage space required to occupy two.

Second, the search algorithm

Finding and sorting are the most basic and important two kinds of algorithms, mastering these two kinds of algorithms skillfully, and can analyze the performance of these algorithms is very important, these two kinds of algorithms mainly include binary search, quick Sort, merge sort and so on.

Sequential Lookup

Sequential lookups are also called linear lookups. Its procedure is: starting from the last element of the lookup table is compared with the given keyword, if a record of the keyword and the given value is equal, the search succeeds, otherwise, until the first record, its keyword and the given value of the comparison are not equal, it indicates that the table does not look for records found unsuccessful, its disadvantage is inefficient.

Two-point Search

    • Brief introduction

Binary search also known as binary lookup, for the ordered table, its advantages are less than the number of comparisons, Find Fast, average performance is good.

The basic idea of binary search is to divide n elements into roughly equal two parts, take A[N/2] and X to compare, if X=A[N/2], then find X, the algorithm aborts, if X<A[N/2], as long as the left half of the array a continues to search X, if X>A[N/2], Search for x in the right half of the array A.

The time complexity of binary lookup is O (logn)

    • Realize
//给定有序查找表array 二分查找给定的值data//查找成功返回下标 查找失败返回-1static int funBinSearch(int[] array, int data) {    int low = 0;    int high = array.length - 1;    while (low <= high) {        int mid = (low + high) / 2;        if (data == array[mid]) {            return mid;        } else if (data < array[mid]) {            high = mid - 1;        } else {            low = mid + 1;        }    }    return -1;}
Third, sorting algorithm

Sorting is an important operation in computer programming, and its function is to rearrange the sequence of a data element (or record) into an ordered sequence by a keyword. The following mainly introduces some of the common sorting algorithms, and analyzes their space-time complexity.


Common sorting algorithms

Common sorting algorithm Performance comparison:


Pictures from the web

There is stability in this table above, and the stability of the order is that if there are two elements of the same order in the sorted sequence, their relative positions are not changed before and after sorting.

The following starts with a bubbling sort.

Bubble sort

    • Brief introduction

The basic idea of bubble sort is: Set the number of records of the sort sequence to N, Carry on the n-1 traverse, each traversal from the starting position in order to compare the neighboring elements, so that the larger elements move backward, and after the end of n-1 traversal, the sequence is orderly.

For example, the process of sequencing a sequence (3,2,1,5) is: A total of 3 traversal, the 1th time elapsed to compare 3 and 2, Exchange, continue to compare 3 and 1, Exchange, and then compare 3 and 5, do not exchange, so that the 1th traversal end, the maximum value 5 in the final position, the resulting sequence (2,1,3,5). The 2nd time period is compared 2 and 1, the exchange, continue to compare 2 and 3, do not exchange, the 2nd traversal at the end of the second large value 3 in the penultimate position, get the sequence (1,2,3,5), 3rd traversal, first compare 1 and 2, do not exchange, get the final ordered sequence (1,2,3,5).

It is important to note that if no interchange occurs in a traversal, then the next traversal is not necessary because the sequence is already in order.

    • Realize
// 冒泡排序 注意 flag 的作用static void funBubbleSort(int[] array) {    boolean flag = true;    for (int i = 0; i < array.length - 1 && flag; i++) {        flag = false;        for (int j = 0; j < array.length - 1 - i; j++) {            if (array[j] > array[j + 1]) {                int temp = array[j];                array[j] = array[j + 1];                array[j + 1] = temp;                flag = true;            }        }    }    for (int i = 0; i < array.length; i++) {        System.out.println(array[i]);    }}
    • Analysis

In the best case, the bubble sort can only be traversed once to determine that the array has been sequenced and does not require the next traversal, so in the best case, the time complexity is O (n) .

In the worst case, the bubble sort requires n-1 traversal, the first traversal needs to compare n-1 times, the second traversal needs to be n-2 times, ..., the last time you need to compare 1 times, the worst case is O (n^2) .

Simple selection sorting

    • Brief introduction

The idea of simple selection sorting is that the number of records for the sequencing sequence is n, the n-1 is selected, and the record with the lowest keyword is selected as the first record in the valid sequence for each record in n-i+1 (i =,..., n-1).

For example, the sequence of sorts (3,2,1,5) is a 3-time selection, a 1th selection of 4 records to select the minimum value of 1, placed in the 1th position, get the sequence (1,3,2,5), 2nd time Select 3 elements starting at position 1 to select the smallest value 2 in the 2nd position, to get ordered sequence ( 1,2,3,5), 3rd time selection because the minimum value of 3 is already in the 3rd position does not need to operate, finally obtains the ordered sequence (1,2,3,5).

    • Realize
static void funSelectionSort(int[] array) {    for (int i = 0; i < array.length - 1; i++) {        int mink = i;            // 每次从未排序数组中找到最小值的坐标        for (int j = i + 1; j < array.length; j++) {            if (array[j] < array[mink]) {                mink = j;            }        }        // 将最小值放在最前面        if (mink != i) {            int temp = array[mink];            array[mink] = array[i];            array[i] = temp;        }    }    for (int i = 0; i < array.length; i++) {        System.out.print(array[i] + " ");    }}
    • Analysis

Simple selection The number of comparisons that need to be made in the sort process is independent of the arrangement of the sequence of records to be sorted in the initial state. When I=1, a n-1 comparison is required, and n-2 comparisons are required when i=2, and so on, the total number of comparisons required is (n-1) + (n-2) +...+2+1=n (n-1)/2, that is, the time complexity of the comparison operation is O (n^2) , The time complexity of the move operation is O (n) . The total time complexity is O (n^2) .

In the best case, the initial state of the records to be sorted is already in a positive order, so you do not need to move the records. In the worst case, the initial state of the records to be sorted is the largest of the first records, and then the records are ordered from small to large, and the maximum number of times to move Records is 3 (n-1).

Simple selection sorting is an unstable sort.

Direct Insert Sort

    • Brief introduction

The idea of direct insertion is to insert a record into an ordered table that is already sorted, resulting in a new, sequential table with a 1 increase in the number of records.

For example, the sequence of sorts (3,2,1,5) is the initial ordered sequence of (3), and then starting at position 1, first access to 2, 2 is inserted before 3, get ordered sequence (2,3), then access 1, find the appropriate insertion position after the ordered sequence (all-in-one), the last access to 5, Get the final ordered sequence (1,2,3,5).

    • Realize
static void funDInsertSort(int[] array) {    int j;    for (int i = 1; i < array.length; i++) {        int temp = array[i];        j = i - 1;        while (j > -1 && temp < array[j]) {            array[j + 1] = array[j];            j--;        }        array[j + 1] = temp;    }    for (int i = 0; i < array.length; i++) {        System.out.print(array[i] + " ");    }}
    • Analysis

In the best case, when the records in the sorted sequence are ordered, a n-1 comparison is required, no movement is required, and the time complexity is O (n) . In the worst case, when all records in the sorted sequence are in reverse order, the number of comparisons and moves reaches the maximum and the time complexity is O (n^2) . On average, the time complexity is O (n^2) .

Hill sort

The hill sort, also known as "narrowing the incremental sort", is an improvement based on the following two-point nature of the direct insert sort: (1) The direct insertion sort is efficient in the case of almost-ordered data operations, i.e., the efficiency of linear sequencing can be achieved. (2) The direct insertion sort is generally inefficient because the insertion sort can only move data one bit at a time. Click here for more information about the hill sort

Merge sort

    • Brief introduction

Merge sort is a typical application of divide-and-conquer method, its main idea is: to divide the sequence to be sorted into two parts, to apply the merge sort recursively to each part, and to combine the two parts after the sequence is arranged.

For example, the process of sorting a sequence (3,2,8,6,7,9,1,5) is to divide the sequence into two parts, (3,2,8,6) and (7,9,1,5), and then apply the merge sort to the two parts, part 1th (3,2,8,6), part 2nd (7,9,1,5), The two sections were sorted by merge, the 1th part continued to be divided into (3,2) and (8,6), (3,2) continued to be divided into (3) and (2), (8,6) continued to be divided into (8) and (6), then merged (2,3), (6,8), then merged (2,3,6,8), The 2nd part is merged and Sorted (1,5,7,9), finally merging two parts to get (1,2,3,5,6,7,8,9).

    • Realize
    Merge sort static void Funmergesort (int[] array) {if (Array.Length > 1) {int length1 = Array.len            GTH/2;            int[] array1 = new INT[LENGTH1];            System.arraycopy (array, 0, array1, 0, length1);            Funmergesort (array1);            int length2 = array.length-length1;            int[] array2 = new Int[length2];            System.arraycopy (Array, length1, Array2, 0, length2);            Funmergesort (array2);            int[] datas = Merge (Array1, array2);        System.arraycopy (datas, 0, array, 0, array.length); }}//merge two arrays of static int[] Merge (int[] List1, int[] list2) {int[] List3 = new Int[list1.length + List2.len        GTH];        int count1 = 0;        int count2 = 0;        int count3 = 0;                while (Count1 < list1.length && Count2 < list2.length) {if (List1[count1] < List2[count2]) {            list3[count3++] = list1[count1++]; } else {list3[count3++] = list2[count2++];        }} while (Count1 < list1.length) {list3[count3++] = list1[count1++];        } while (Count2 < list2.length) {list3[count3++] = list2[count2++];    } return LIST3; }
    • Analysis

The time complexity of the merge sort is O (Nlogn), which is a stable sort, and the sort method in the Java.util.Arrays class is implemented using a variant of the merge sort.

Quick Sort

    • Brief introduction

The main idea of a quick sort is to select an element called a principal in the sequence to be sorted, divide the array into two parts, make all the elements in the first part less than or equal to the principal, and all the elements in the second part are larger than the principal, and then apply the quick Sort algorithm recursively to the two parts.

    • Realize
Quick sort static void Funquicksort (int[] mdata, int start, int end) {if (end > Start) {int pivotindex = quicks        Ortpartition (Mdata, start, end);        Funquicksort (Mdata, start, pivotIndex-1);    Funquicksort (Mdata, Pivotindex + 1, end);    }}//Fast Sort before the division of the static int quicksortpartition (int[] list, int first, int last) {int pivot = List[first];    int low = first + 1;    int high = last;        while (High > Low) {while (Low <= high && List[low] <= pivot) {low++;        {<= high && List[high] > Pivot) {high--;            } if (High > low) {int temp = List[high];            List[high] = List[low];        List[low] = temp;    }} while (High > First && list[high] >= pivot) {high--;        } if (Pivot > List[high]) {List[first] = List[high];        List[high] = pivot;    return high;    } else {return first; }}
    • Analysis

In the fast sorting algorithm, one of the key parts is the selection of the main element. In the worst case, dividing an array of n elements requires n-comparisons and N-Moves, so the time to divide is O (n). In the worst case, each time the main element divides the array into a large subarray and an empty array, the size of the large sub-array is reduced by 1 on the scale of the last sub-array, so that in the worst case the algorithm needs (n-1) + (n-2) +...+1= O (n^2) time.

In the best case, each time the main element divides the array into two parts of roughly equal size, the time complexity is O (NLOGN) .

Heap Sort

    • Brief introduction

Before describing heap sequencing, you first need to understand the definition of the heap, n a sequence of k1,k2,...,kn called Heaps, when and only if the sequence satisfies the following properties (for short, heap properties): (1) Ki <= K (2i) and Ki <= K (2i+1) (1≤I≤N/2), of course, this is the small Gan , the Dagen is replaced by the >= number.

If a sequence that satisfies the heap is considered to be a complete binary tree, the meaning of the heap indicates that the values of all non-endpoints in the full binary tree are not greater than (or not less than) the values of their left and right child nodes.

The main idea of heap ordering is: Given a sequence to be sorted, first after the adjustment, the sequence is constructed into a large top heap, at which time the first element is the largest element, it is exchanged with the last element of the sequence, then the first n-1 elements are adjusted to the large top heap, and then the element and the end element are exchanged. This gives an ordered sequence at the end.

    • Realize
Heap sort public class Testheapsort {public static void main (string[] args) {int arr[] = {5, 6, 1, 0, 2, 9};        Heapsort (arr, 6);    System.out.println (arrays.tostring (arr));            } static void Heapsort (int arr[], int n) {//First build large top heap for (int i = N/2-1; I >= 0; i--) {        Heapadjust (arr, I, N);            } for (int i = 0; i < n-1; i++) {swap (arr, 0, n-i-1);        Heapadjust (arr, 0, n-i-1);        }}//Exchange two number static void swap (int arr[], int low, int high) {int temp = Arr[low];        Arr[low] = Arr[high];    Arr[high] = temp;        }//Adjust heap static void Heapadjust (int arr[], int index, int n) {int temp = Arr[index];        int child = 0;            while (Index * 2 + 1 < n) {child = index * 2 + 1;            The child is the larger of the left and right children if (son! = n-1 && Arr[child] < Arr[child + 1]) {child++; }//If the specified node is larger than the child does not needTo adjust if (temp > Arr[child]) {break;                } else {//otherwise continue to judge children's children until they find the right place arr[index] = Arr[child];            index = child;    }} Arr[index] = temp; }}
    • Analysis

Heap sorting is not appropriate for files with fewer records due to the number of comparisons required to build the initial heap. Heap sorting time complexity is also O (NLOGN), the space complexity is O (1). It is an unstable sort method. Compared with the fast row and merge sort, the time complexity of heap sorting in the worst case is better than that of fast row, the space efficiency is higher than the merge sort.

Iv. Other algorithms

In the above space, mainly on the search and common several sorting algorithms are introduced, these content are basic but must master the content, especially the binary search, fast row, heap row, merge sort these are the interview of high-frequency research point. (here can not help but think of Baidu side of the time let me write two points to find and heap sorting, binary search is also OK, but heap sort at that time a face Meng ... The following is mainly about some of the other common algorithms.

Recursive

    • Brief introduction

Recursion is often used when solving some programming or algorithmic problems. The programming technique called by the program itself is called recursion. It often transforms a large complex problem layer into a smaller problem that is similar to the original problem. The idea of recursion is used in the quick sort and merge sort described above.

    • Classic examples

Fibonacci series, also known as the Golden section of the series, because of the mathematician Leonardo's Fibonacci to the rabbit breeding as an example of the introduction, so called "Rabbit series", refers to such a series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 、...... Mathematically, the Fibonacci sequence is defined as a recursive method: F (0) =0,f (1) =1,f (n) =f (n-1) +f (n-2) (n≥2,n∈n*).

//斐波那契数列 递归实现static long funFib(long index) {    if (index == 0) {        return 0;    } else if (index == 1) {        return 1;    } else {        return funFib(index - 1) + funFib(index - 2);    }}

The above code is the recursive implementation of the Fibonacci sequence, however it is not difficult to get its time complexity is O (2^n), recursion can sometimes easily solve some problems, but it also brings some efficiency problems. The following code is another way to find the Fibonacci sequence, which is more efficient than the recursive method.

static long funFib2(long index) {    long f0 = 0;    long f1 = 1;    long f2 = 1;    if (index == 0) {        return f0;    } else if (index == 1) {        return f1;    } else if (index == 2) {        return f2;    }    for (int i = 3; i <= index; i++) {        f0 = f1;        f1 = f2;        f2 = f0 + f1;    }    return f2;}

Divide and conquer algorithm

The idea of divide-and-conquer algorithm is to decompose the problem into several smaller but similar sub-problems, to solve these sub-problems recursively, and then merge the solutions of these sub-problems to establish the final solution. The key step in the divide-and-conquer algorithm is actually to solve the sub-problem recursively. A typical example of a divide-and-conquer algorithm is the merge sort described above. Read more about divide and conquer algorithms

Dynamic planning

The dynamic programming is similar to the method of divide and conquer, which solves the problem by the solution of the combinatorial sub-problem. However, the divide-and-conquer algorithm divides the problem into sub-disjoint problems, solves the sub-problems recursively, and then combines their solutions, while the dynamic programming is applied to the overlapping of sub-problems, that is, the sub-problems have the common child sub-problems. The dynamic programming method is often used to solve optimization problems. See more about dynamic planning

A typical example of dynamic programming is the longest common subsequence problem.

There are many common algorithms, such as greedy algorithm, backtracking algorithm and so on, here are no longer detailed introduction, want to master, or rely on brush questions, brush questions, brush questions, and then summarize.

Five, common algorithm problem

The following is a summary of some common algorithmic questions.

Exchange two numbers without using a temporary variable

static void funSwapTwo(int a, int b) {    a = a ^ b;    b = b ^ a;    a = a ^ b;    System.out.println(a + " " + b);}

Determine whether a number is prime

static boolean funIsPrime(int m) {    boolean flag = true;    if (m == 1) {        flag = false;    } else {        for (int i = 2; i <= Math.sqrt(m); i++) {            if (m % i == 0) {                flag = false;                break;            }        }    }    return flag;}

Other Algorithmic questions

1.15-channel basic arithmetic problem with very high frequency
2. Binary Tree Related algorithm problem
3. Linked list related algorithm problem
4, String correlation algorithm problem

Vi. Summary

The above is their own common algorithm related content summary, algorithm abuse me times, I wait for algorithm such as First love, revolution has not succeeded, comrade still need to brush questions, refueling.



Dust Language Temptations
Links: http://www.jianshu.com/p/42f81846c0fb
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

"Turn" data structure and algorithm (bottom)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.