Introduction to Algorithms note 3

Summary

How to design algorithms

2.3 Design Algorithm

There are many algorithm design, insertion sort incremental method, the sorted subarray A [1..j-1] after the individual elements into place, generating sub-arrays A [1..j]. Another way to think below divide and conquer, divide and conquer in the worst case running time of insertion sort is much less than that, one of the advantages is often very easy to determine the running time.

2.3.1 Divide and Conquer

Many useful algorithms in the structure is recursive. Ideological divide and conquer: the original problem into several smaller-scale but similar sub-problems of the original problem, recursive solving these sub-problems, then de-merger of these sub-issues of establishing solution of the original problem.

Each recursive partition in three steps:
decomposing the original problem into sub-problems, to solve the sub-problem solutions combined solution to the original problem of sub-problems.

Follow the partition merge sort method:
the decomposition of n elements to be sorted into two sub-sequences having n / 2 elements. Recursively using merge sort ordering two sub-sequences, sequences merge two sorted generate sorted out.

Core code

package notes.javase.algorithm.sort;

public class MergeSort {
    public void Merge(int[] array, int low, int mid, int high) {
        int i = low; // i是第一段序列的下标
        int j = mid + 1; // j是第二段序列的下标
        int k = 0; // k是临时存放合并序列的下标
        int[] array2 = new int[high - low + 1]; // array2是临时合并序列

        // 扫描第一段和第二段序列,直到有一个扫描结束
        while (i <= mid && j <= high) {
            // 判断第一段和第二段取出的数哪个更小,将其存入合并序列,并继续向下扫描
            if (array[i] <= array[j]) {
                array2[k] = array[i];
                i++;
                k++;
            } else {
                array2[k] = array[j];
                j++;
                k++;
            }
        }

        // 若第一段序列还没扫描完,将其全部复制到合并序列
        while (i <= mid) {
            array2[k] = array[i];
            i++;
            k++;
        }

        // 若第二段序列还没扫描完,将其全部复制到合并序列
        while (j <= high) {
            array2[k] = array[j];
            j++;
            k++;
        }

        // 将合并序列复制到原始序列中
        for (k = 0, i = low; i <= high; i++, k++) {
            array[i] = array2[k];
        }
    }

    public void MergePass(int[] array, int gap, int length) {
        int i = 0;

        // 归并gap长度的两个相邻子表
        for (i = 0; i + 2 * gap - 1 < length; i = i + 2 * gap) {
            Merge(array, i, i + gap - 1, i + 2 * gap - 1);
        }

        // 余下两个子表,后者长度小于gap
        if (i + gap - 1 < length) {
            Merge(array, i, i + gap - 1, length - 1);
        }
    }

    public int[] sort(int[] list) {
        for (int gap = 1; gap < list.length; gap = 2 * gap) {
            MergePass(list, gap, list.length);
            System.out.print("gap = " + gap + ":t");
            this.printAll(list);
        }
        return list;
    }

    // 打印完整序列
    public void printAll(int[] list) {
        for (int value : list) {
            System.out.print(value + "t");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] array = {
                9, 1, 5, 3, 4, 2, 6, 8, 7
        };

        MergeSort merge = new MergeSort();
        System.out.print("排序前:tt");
        merge.printAll(array);
        merge.sort(array);
        System.out.print("排序后:tt");
        merge.printAll(array);
    }
}

Big Box  Introduction to Algorithms note 3 "title =" merge sort of efficiency: "> merge sort of efficiency:

Time complexity: merge sort is in the form of a binary tree, the number of times it is needed to traverse the binary tree of depth, and the complete binary tree can be derived in accordance with its time complexity is O (log n-* 2 n-).

Space complexity: By the above described algorithm, the algorithm process, requires a size of n temporary storage to save the merged sequence.

Stability algorithms: merge sort in order of equal elements will not change, so it is stable algorithm.

Compare merge sort and heap sort, quick sort of

  • If the space complexity to consider: Preferred heap sort, followed by quick sort, and finally merge sort.
  • When considered from the stability should be selected merge sort, because the heap sort and quick sort are unstable.
  • Considering the speed of ordering from the average case, you should select Quick Sort.

Exercise

1. binary search

Recursive algorithm is given, obviously the worst case running time is O (log 2 n-)

/**
 * 二分查找,找到该值在数组中的下标,否则为-1
 */
static int binarySerach(int[] array, int key) {
    int left = 0;
    int right = array.length - 1;

    // 这里必须是 <=
    while (left <= right) {
        int mid = (left + right) / 2;
        if (array[mid] == key) {
            return mid;
        }
        else if (array[mid] < key) {
            left = mid + 1;
        }
        else {
            right = mid - 1;
        }
    }

    return -1;
}

2. Find improving with binary insertion sort can improve the total running time

//二分查找  
public static int binarySearch(int array[],int low,int high,int temp)  
{  
    int mid=0;  
    while(low<=high)  
    {  
        mid=(low+high)/2;  
        if(array[mid]<temp&&temp<=array[mid+1])  
            return (mid+1);  
        else if(array[mid]<temp)  
            low = mid + 1;  
        else  
            high = mid -1;  
    }  
    return high;  
}

//二分排序  
public static void binarySort(int array[],int size)  
{  
    int i,j,k,temp;
    for(i=1;i<size;i++)  
    {  
        temp=array[i];  
        if(array[i]<array[0])  
            k=0;  
        else  
            k = binarySearch(array,0,i,temp);  

        for(j=i;j>k;j--)  
        {  
            array[j]=array[j-1];  
        }  
        array[k]=temp;  
        System.out.println(Arrays.toString(array));  
    }  
}

In the worst case, a binary search time complexity is nlgn, but the time complexity of the array is still moving during insertion n- 2 . It does not improve the overall run time is O (nlgn), but if the data structure used to sort the list, can be improved.

3 describes a run time of O (nlgn) algorithm, a given set S of n integers x and another integer, the algorithm can determine whether there are two S which is exactly engaged element x

Input: Array A, x integer
pseudocode:

A=Sort(A)//对数组A排序
n=length[A]//n为数组A的长度
for i=0 to n-1 do
    if A[i]>=0 and Binary_search(A,x-A[i],1,n) then //用二分查找看x-A[i]是否在数组A中
        return true
    end if
end for
return false

Guess you like

Origin www.cnblogs.com/liuzhongrong/p/12434241.html