It is known that for a list of length n , on average, the insertion sort makes ( n 2 + 3 n – 4) / 4 key comparisons and about n ( n – 1) / 4 item assignments
Therefore, if n = 1000, then to sort the list, the insertion sort makes about 250,000 key comparisons and about 250,000 item assignments
26.
Sequential Ordered Search public static int seqOrderedSearch( int [] list, int listLength, int searchItem) { int loc; //Line 1 boolean found = false ; //Line 2 for (loc = 0; loc < listLength; loc++) //Line 3 if (list[loc] >= searchItem) //Line 4 { found = true ; //Line 5 break ; //Line 6 } if (found) //Line 7 if (list[loc] == searchItem) //Line 8 return loc; //Line 9 else //Line 10 return -1; //Line 11 else //Line 12 return -1; //Line 13 }
31.
Binary Search Algorithm (continued) public static int binarySearch( int [] list, int listLength, int searchItem) { int first = 0; int last = listLength - 1; int mid; boolean found = false ; while (first <= last && !found) { mid = (first + last) / 2; if (list[mid] == searchItem) found = true ; else if (list[mid] > searchItem) last = mid - 1; else first = mid + 1; } if (found) return mid; else return –1; } //end binarySearch
To determine whether an element is in L , binary search makes at most 42 item comparisons
On the other hand, on average, a sequential search will make 500,000 key (item) comparisons to determine whether an element is in L
In general, if L is a sorted list of size n , to determine whether an element is in L , the binary search makes at most 2log2 n + 2 key (item) comparisons
Views
Actions
Embeds 0
Report content