python 无序列表中第k大元素_查询无序列表中第K小元素
當需要在無需列表中尋找第k小的元素時,一個顯然的方法是將所有數據進行排序,然后檢索k個元素。這種方法的運行時間為O(n log(n))。
無序列表調用分區函數將自身分解成兩個子表,其長度為i和n-i。第一個列表中的第一個i元素(不一定排序),當i與k進行比較時需在第一或第二個子列表中搜索元素。
使用findMinK(ArrayListarray, int k, int i, int r)實現,同時使用下面testframe代碼測試。在函數中可增加全局變量cmpcnt,在列表中利用分區函數交換元素時計數。
對findMinK函數的實現,利用了快排的思想:
先從n個元素中找一個任意分界點,設為m,假設m在列表中的位置是i
先從n個元素中隨便尋找一個數m作為分界點,m在列表中的位置為i
當 i = k時,m就是我們要尋找的第k小的數;
當 i > k時,我們就從1~i-1中查找;
當?i < k時,就從i+1~n中查找。
下面是代碼實現:
packagedisorder_List;importjava.util.ArrayList;importjava.util.Collections;importjava.util.Random;public classTestDisorder {static public int cmpcnt = 0;public static voidmain(String[] args) {
testFramework();
}public static int partion(ArrayList A,int low,inthigh){int pivotkey=A.get(low);while(low=pivotkey)
high--;
A.set(low, A.get(high));
cmpcnt++;while(low
low++;
A.set(high, A.get(low));
cmpcnt++;
}
cmpcnt++;
A.set(low, pivotkey);returnlow;
}public static int findMinK(ArrayList array, int k, int l, intr) {//Implement here
if(l<=r){int pivotloc=partion(array, l, r);if(pivotloc==k-1){returnarray.get(pivotloc);
}else if(pivotloc
}else{return findMinK(array, k,l,pivotloc-1);
}
}else{return -1;
}
}public static int findMinK(ArrayList array, intk){
Collections.sort(array);return array.get(k-1);
}private static voidtestFramework() {
ArrayList a = new ArrayList();for (int j=2;j<8;j++){
a.clear();for (int i=0;i
a.add(i);
}
System.out.println("nn"+a.size()+" Elementsnn");double slow=0;double fast=0;for (int i = 0; i < 2; i++) {
cmpcnt= 0;
Collections.shuffle(a);int k = (int)(Math.random()*(Math.pow(10, j)-1))+1;
System.out.println("test run number: " + i + " find: " +k);long start =System.currentTimeMillis();int resulta = findMinK(a, k, 0, a.size()-1);long end =System.currentTimeMillis();long smarttime=(end-start);
fast= fast +smarttime;
System.out.println("SMART ALGO t --- time in ms: " + smarttime + " comparisons: "
+cmpcnt);
start=System.currentTimeMillis();int resultb=findMinK(a, k);
end=System.currentTimeMillis();long slowtime = (end-start);
System.out.println("WITH SORTING t --- time in ms: " +slowtime);
slow= slow +slowtime;
}
System.out.println("sorting (="+slow+"ms) is " +slow/fast + " times slower than smart algo (="+fast+"ms)");
}
}
}
View Code
以下是部分輸出結果:
sorting (=3.0ms) is 3.0 times slower than smart algo (=1.0ms)
sorting (=24.0ms) is 12.0 times slower than smart algo (=2.0ms)
sorting (=41.0ms) is 8.2 times slower than smart algo (=5.0ms)
sorting (=401.0ms) is 4.773809523809524 times slower than smart algo (=84.0ms)
....
可明顯看出該方法的優勢。
總結
以上是生活随笔為你收集整理的python 无序列表中第k大元素_查询无序列表中第K小元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 神经网络python识别词语_请教关于p
- 下一篇: Appium python adb命令