zoukankan      html  css  js  c++  java
  • java中经典算法及其代码整理

    一、选择排序法

    public static void selectSort(int[] a){
        int minIndex = 0;
        int temp = 0;
        if(a == null)||(a.length == 0){
            return;
        }
        for(i = 0; i < a.length-1; i++){
            minIndex = i;
            for(j = i+1; j < a.length; j++){
                if(a[j] < a[minIndex]){
                    minIndex = j;
                }
            }
            if(minIndex != i){  //如果a[i]不是最小值,则将最小值放在a[i]位置
                temp = a[i];
                a[i] = a[minIndex];
                a[minIndex] = temp;
            }
        }
    }

    二、冒泡排序法

    public static void BubbleSort(int[] a){
        int temp = 0;
        for(i = 0; i < a.length; i++){
            for(j = 1; j < a.length-i; j++){
                if(a[i] < a[j]){
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
    }

    三、快速排序法

    public class QuickSort{
        public void quickSort(int[] arr, low, high){
            if(low < high){
                int privotpos = partition(arr, low, high);
                quickSort(arr,low,privotpos-1);
                quickSort(arr,privotpos+1, high);
            }
        }
    
        public int partition(int[] arr, low, high){
            int privot = arr[low];
            while(low < high){
                while(low < high %& arr[low] <= privot) ++low;
                pritition = arr[low];
                while(low < high %& arr[high] >= privot) --high;
                privot = arr[high];
            }
            a[low]  = privot;
        }
    }

    四、二分查找法

    public int binarySearch(int arr[], int key){
        int low = 0, high = arr.length, mid;
        while(low <= high){
            mid = (low + high) / 2;
            if(key == arr[mid]){
                return mid;
            }else if(key < arr[mid]){
                high = mid - 1; 
            }else{
                low = mid + 1;
            }
        }
        return -1;
    }
  • 相关阅读:
    洛谷P1908《逆序对》
    洛谷P3884《[JLOI2009]二叉树问题》
    最近公共祖先 LCA
    洛谷P1531《I Hate It》
    洛谷P1563「NOIP2016」《玩具谜题》
    乘法逆元求法
    CF56E 【Domino Principle】
    CF638C 【Road Improvement】
    Luogu
    2018.8.7提高B组模拟考试
  • 原文地址:https://www.cnblogs.com/mercuryji/p/Algorithms_sort.html
Copyright © 2011-2022 走看看