performance - Avg number of comparisons for failure in this sequential search algorithm? -
performance - Avg number of comparisons for failure in this sequential search algorithm? -
the algorithm:
public boolean search(int[] a, int target) { for(int i=0;i<a.length;i++) { if(target==a[i]) homecoming true; if(target<a[i]) homecoming false; } homecoming false; }
i'm having problem understanding problem - know has series, introduction of 2 comparisons per iteration has me stumped. can help me out , explain me?
how used @ was:
think of best case, whats to the lowest degree possible comparisons can have? when:
target==a[0] //first element
think of worst case, whats comparisons can have? when:
target==a[a.length-1] ///last elements or not found
so our average case?
well take consideration first element fast, lastly element slow (o(1) vs o(n)) move away begginning starts taking longer, @ same time away end gets faster. average case lie in middle.
if looking specific number avg number of comparisons might be
3 comparisons "for comparrison,target == a[i], target < a[i] times n/2 " our average number of comparissons
if want test can create counter , increment 1 everytime comparing in algorithm
performance search average
Comments
Post a Comment