[英]Analysis algorithm Best, Worst and Average case
我想知道find和replaceAll方法的最佳,最差和平均情況是什么,以及增長函數,基本上是以下代碼中數組大小大於零的每種情況下執行的語句數
/**
* Return index where value is found in array or -1 if not found.
* @param array ints where value may be found
* @param value int that may be in array
* @return index where value is found or -1 if not found
*/
public static int find(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
/**
* Replace all occurrences of oldValue with newValue in array.
* @param array ints where oldValue may be found
* @param oldValue value to replace
* @param newValue new value
*/
public static void replaceAll(int[] array, int oldValue, int newValue) {
int index = find(array, oldValue);
while (index > -1) {
array[index] = newValue;
index = find(array, oldValue);
}
}
這是用於find(...)方法
您可以輕松了解最佳和最差情況:
最好的情況是,要搜索的元素是數組中的第一個元素。 在這種情況下,只需1次迭代即可找到您的元素,即O(1)
恆定時間。
同樣,最壞的情況是要搜索的元素在數組中不存在,因此您遍歷整個數組只是什么也找不到。 在這種情況下,它需要進行n次迭代(其中n是數組的大小),線性時間為O(n)
。
大多數情況下,很容易確定最壞的情況。 您可以簡單地查看嵌套循環。 如果您有x
個嵌套循環,其中所有循環都以線性時間遍歷數組,則您的時間復雜度為O(n ^ x)。 所以在的replaceAll(...),你有2個嵌套循環( while
並for
您find(...)
方法),這意味着復雜度為O(n^2)
最壞情況replaceAll(...)
對於一般情況:
我為您的find(...)
函數編寫了一個測試:
public static void main(String[] args) {
int iterationsTotal = 0;
int timesTested = 100000;
//Test 1000 times
for(int i = 0; i < timesTested; i++) {
int n = 100; //Array size to test
int[] array = new int[n];
//Populate the array
int j = 0;
for(j = 0; j < array.length; j++) {
array[j] = (int)(Math.random() * 100);
}
//You can search for any number, even 99. It will always result in 25 average.
iterationsTotal += find(array, 5);
}
System.out.println(iterationsTotal / timesTested);
}
上面的代碼測試您的find函數100,000次。 它計算平均迭代次數,每次運行時通常約為25次。 使用大小為100的數組,平均進行25次迭代以查找要搜索的元素。 這就是O(n/4)
,其中n =數組的大小,在這種情況下為100。這與O(n)一樣好( 為什么在計算算法的運行時間復雜度時忽略常量 )。 因此,對於您的find(...)
算法,平均情況為O(n)。 您可以對replaceAll(...)
執行相同的操作
找
全部替換
生長功能?
我希望這可以幫到你。
O(n^2)
n
次迭代中運行 n^2
次迭代中運行 O(n)
如果要在O(n)
進行創建,則在使用find
時需要傳遞起始索引,因此不必從數組的開頭重復搜索
public static int find(int[] array, int value, int start) {
for (int i = start; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
public static void replaceAll(int[] array, int oldValue, int newValue) {
int index = find(array, oldValue);
while (index > -1) {
array[index] = newValue;
index = find(array, oldValue, index);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.