Created
October 15, 2012 19:57
-
-
Save joequery/3894914 to your computer and use it in GitHub Desktop.
Divide and conquer approach to finding index of largest element in a list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Yay school. | |
| def find_largest(mylist): | |
| if len(mylist) == 1: | |
| return 0 | |
| elif len(mylist) == 2: | |
| if mylist[0] > mylist[1]: | |
| return 0 | |
| else: | |
| return 1 | |
| else: | |
| m = len(mylist) / 2 | |
| blist = mylist[0:m] | |
| clist = mylist[m:len(mylist)] | |
| largest_b = find_largest(blist) | |
| largest_c = find_largest(clist) + m | |
| if mylist[largest_b] > mylist[largest_c]: | |
| return largest_b | |
| else: | |
| return largest_c | |
| mylist = [100,15,85,20,25] | |
| largest = find_largest(mylist) | |
| print("Largest: %d. Largest element: %d" % (largest, mylist[largest])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment