算法模板

算法模板

1.递归模板

1.1递归

public class recursion {
    public void recur(int level,int param) {

        //terminator  终结条件
        if(level > level) {
            //process result  处理结果
            return;
        }

        //process current logic  当前逻辑主过程
        Process(level,param);

        //drill down         向下递归
        recur(level;level+1,newParam);

        //restore current status    清除本层次递归的状态
    }
}

1.2回溯

result = [];
function backtrack (path, list) {
    if (满足条件) {
        result.push(path);
        return
    }
    
    for () {
        // 单层逻辑
        backtrack (path, list)
        // 撤销选择 重置状态
    }
}

2.二叉堆

package com.aiden;

import java.util.Arrays;
import java.util.NoSuchElementException;

public class BinaryHeap {

    private static final int d = 2;
    private int[] heap;
    private int heapSize;

    /**
     * This will initialize our heap with default size.
     */
    public BinaryHeap(int capacity) {
        heapSize = 0;
        heap = new int[capacity];
        Arrays.fill(heap, -1);
    }

    public boolean isEmpty() {
        return heapSize == 0;
    }

    public boolean isFull() {
        return heapSize == heap.length;
    }

    private int parent(int i) {
        return (i - 1) / d;
    }

    private int kthChild(int i, int k) {
        return d * i + k;
    }

    /**
     * Inserts new element in to heap
     * Complexity: O(log N)
     * As worst case scenario, we need to traverse till the root
     */
    public void insert(int x) {
        if (isFull()) {
            throw new NoSuchElementException("Heap is full, No space to insert new element.");
        }
        heap[heapSize++] = x;
        heapifyUp(heapSize - 1);
    }

    /**
     * Deletes element at index x
     * Complexity: O(log N)
     */
    public int delete(int x) {
        if (isEmpty()) {
            throw new NoSuchElementException("Heap is empty, No element to delete");
        }
        int key = heap[x];
        heap[x] = heap[heapSize - 1];
        heapSize--;
        heapifyDown(x);
        return key;
    }

    /**
     * Maintains the heap property while inserting an element.
     */
    private void heapifyUp(int i) {
        int insertValue = heap[i];
        while (i > 0 && insertValue > heap[parent(i)]) {
            heap[i] = heap[parent(i)];
            i = parent(i);
        }
        heap[i] = insertValue;
    }

    /**
     * Maintains the heap property while deleting an element.
     */
    private void heapifyDown(int i) {
        int child;
        int temp = heap[i];
        while (kthChild(i, 1) < heapSize) {
            child = maxChild(i);
            if (temp >= heap[child]) {
                break;
            }
            heap[i] = heap[child];
            i = child;
        }
        heap[i] = temp;
    }

    private int maxChild(int i) {
        int leftChild = kthChild(i, 1);
        int rightChild = kthChild(i, 2);
        return heap[leftChild] > heap[rightChild] ? leftChild : rightChild;
    }

    /**
     * * Prints all elements of the heap
     */

    public void printHeap() {
        System.out.print("nHeap = ");
        for (int i = 0; i < heapSize; i++)
            System.out.print(heap[i] + " ");
        System.out.println();
    }

    /**
     * * This method returns the max element of the heap.
     * <p>
     * <p>
     * * complexity: O(1)
     */

    public int findMax() {
        if (isEmpty())
            throw new NoSuchElementException("Heap is empty.");
        return heap[0];
    }

    public static void main(String[] args) {
        BinaryHeap maxHeap = new BinaryHeap(10);
        maxHeap.insert(10);
        maxHeap.insert(4);
        maxHeap.insert(9);
        maxHeap.insert(7);
        maxHeap.insert(5);
        maxHeap.insert(8);
        maxHeap.insert(6);
        maxHeap.insert(2);
        maxHeap.insert(3);
        maxHeap.insert(1);
        maxHeap.printHeap();
        maxHeap.delete(4);
        maxHeap.printHeap();
        maxHeap.delete(2);
        maxHeap.printHeap();
    }
}

3.堆排序

public class HeapSort {
    public static void heapSort(int[] array) {
        if (array.length == 0) return;
        int length = array.length;
        for (int i = length / 2 - 1; i >= 0; i--) {
            heapify(array, length, i);
        }
        for (int i = length - 1; i >= 0; i--) {
            int temp = array[0];
            array[0] = array[i];
            array[i] = temp;
            heapify(array, i, 0);
        }
    }

    public static void heapify(int[] array, int length, int i) {
        int left = 2 * i + 1, right = 2 * i + 2;
        int largest = i;
        if (left < length && array[left] > array[largest]) {
            largest = left;
        }
        if (right < length && array[right] > array[largest]) {
            largest = right;
        }
        if (largest != i) {
            int temp = array[i];
            array[i] = array[largest];
            array[largest] = temp;
            heapify(array, length, largest);
        }
    }
}

4.快速排序

public class QuickSort {
    public void quickSort(int[] array, int begin, int end) {
        if (end <= begin) {
            return;
        }
        int pivot = partition(array, begin, end);
        quickSort(array, begin, pivot);
        quickSort(array, pivot + 1, end);
    }

    public int partition(int[] array, int begin, int end) {
        int counter = begin;
        for (int i = begin; i < end; ++i) {
            if (array[i] < array[end]) {
                int temp = array[i];
                array[i] = array[counter];
                array[counter++] = temp;
            }
        }
        int temp = array[counter];
        array[counter] = array[end];
        array[end] = temp;
        return counter;
    }
}

5.归并排序

public class MergeSort {
    public void mergeSort(int[] nums, int begin, int end) {
        if (end <= begin) {
            return;
        }
        int middle = begin + (end - begin) / 2;
        mergeSort(nums, begin, middle);
        mergeSort(nums, middle + 1, end);
        merge(nums, begin, middle, end);
    }

    public void merge(int[] nums, int begin, int middle, int end) {
        int[] mm = new int[end - begin + 1];
        int left = begin, right = middle + 1, k = 0;
        while (left <= middle && right <= end) {
            mm[k++] = nums[left] > nums[right] ? nums[right++] : nums[left++];
        }
        while (left <= middle) {
            mm[k++] = nums[left++];
        }
        while (right <= end) {
            mm[k++] = nums[right++];
        }
        for (int i = 0; i < k; ++i) {
            nums[i + begin] = mm[i];
        }
    }
}
posted @ 2023-02-02 15:22  一步两世  阅读(21)  评论(0)    收藏  举报