常用算法

二分查找

public static int indexOf(int[] a, int key) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            // Key is in a[lo..hi] or not present.
            int mid = lo + (hi - lo) / 2;
            if      (key < a[mid]) hi = mid - 1;
            else if (key > a[mid]) lo = mid + 1;
            else return mid;
        }
        return -1;
    }

快速排序

public static void sort(Comparable[] a) {
        StdRandom.shuffle(a);
        sort(a, 0, a.length - 1);
        assert isSorted(a);
    }

    // quicksort the subarray from a[lo] to a[hi]
    private static void sort(Comparable[] a, int lo, int hi) { 
        if (hi <= lo) return;
        int j = partition(a, lo, hi);
        sort(a, lo, j-1);
        sort(a, j+1, hi);
        assert isSorted(a, lo, hi);
    }

    // partition the subarray a[lo..hi] so that a[lo..j-1] <= a[j] <= a[j+1..hi]
    // and return the index j.
    private static int partition(Comparable[] a, int lo, int hi) {
        int i = lo;
        int j = hi + 1;
        Comparable v = a[lo];
        while (true) { 

            // find item on lo to swap
            while (less(a[++i], v)) {
                if (i == hi) break;
            }

            // find item on hi to swap
            while (less(v, a[--j])) {
                if (j == lo) break;      // redundant since a[lo] acts as sentinel
            }

            // check if pointers cross
            if (i >= j) break;

            exch(a, i, j);
        }

        // put partitioning item v at a[j]
        exch(a, lo, j);

        // now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi]
        return j;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 排序算法算法 時(shí)間復(fù)雜度看看有幾重for循環(huán),只有一重則時(shí)間復(fù)雜度為O(n),二重則為O(n^2),依此類(lèi)推,如果...
    wayDevelop閱讀 1,064評(píng)論 0 1
  • 1. 快速排序 快速排序是由東尼·霍爾所發(fā)展的一種排序算法。在平均狀況下,排序 n 個(gè)項(xiàng)目要Ο(n log n)次...
    Sunface撩技術(shù)閱讀 2,808評(píng)論 1 5
  • 轉(zhuǎn)自Android訂閱 第一 快速排序算法 快速排序是由東尼·霍爾所發(fā)展的一種排序算法。在平均狀況下,排序 n 個(gè)...
    葛藤灣閱讀 482評(píng)論 0 2
  • [TOC] 排序 冒泡排序法 冒泡排序法,利用兩層嵌套循環(huán),相鄰數(shù)據(jù)進(jìn)行比較,每次內(nèi)層循環(huán)結(jié)束,把當(dāng)前最大數(shù)交換到...
    淺顏如夢(mèng)閱讀 466評(píng)論 0 0
  • 沒(méi)錯(cuò)沒(méi)錯(cuò),朋友圈有時(shí)候真的很會(huì)惹禍!~ 不信你聽(tīng)我娓娓道來(lái)。今年五月份聽(tīng)了蒙氏的課,有小伙伴推薦我再學(xué)個(gè)思維導(dǎo)圖!...
    BLACKSWAN如閱讀 601評(píng)論 0 0

友情鏈接更多精彩內(nèi)容