# Hello World program in Python from data import DataNode from stack import Stack import sort import math def reverse_string(ostr): st = Stack() rstr = "" for i in range(0,len(ostr)): st.push(ostr[i]) while not(st.isempty()): rstr += st.pop() return rstr def bubble_sort(usorted): i=0 n=len(usorted)-1 ctr=0 swapped = False while n > 0 : for i in range(0,n): j = i +1 ctr += 1 if usorted[i] > usorted[j]: temp = usorted[i] usorted[i] = usorted[j] usorted[j] = temp swapped=True if not swapped: break n -= 1 print("total inner loop count "+ str(ctr)) print("sorted data "+ str(usorted)) return usorted #def is_sorted def binary_search(x,srcstr): print("=============Starting Binary Search =====================") sortedstr = bubble_sort(srcstr) print("Sorted data "+str(sortedstr)) low = 0 high = len(sortedstr)-1 ctr=mid=0 while low <= high: ctr+=1 print("low %d mid %d high %d" % (low,mid, high)) mid = (low + high)//2 print(" mid "+str(mid)) if sortedstr[mid]==x: return str(x)+" is found at index "+str(mid)+".Total loops "+str(ctr) elif sortedstr[mid] < x: low = mid + 1 else: high = mid - 1 return str(x)+" is not present in search string.Total loops "+str(ctr) def interpolation_search(x,srcstr): print("=============Starting interpolation Search =====================") sortedstr = bubble_sort(srcstr) print("Sorted data "+str(sortedstr)) low = 0 high = len(sortedstr)-1 ctr = mid = 0 while low < high: ctr +=1 print("low %d mid %d high %d" % (low,mid, high)) mid = min(math.ceil(low + ((high-low)/(srcstr[high]-srcstr[low]))*(x-srcstr[low])),high) print("mid %d str %d" % (mid, sortedstr[mid])) if sortedstr[mid]==x: return str(x)+" is found at index "+str(mid)+". Total loops "+str(ctr) elif sortedstr[mid] < x: low = mid + 1 else: high = mid - 1 return str(x)+" is not present in search string. Total loops "+str(ctr) #dn1 = DataNode(5) #dn2 = DataNode(6) #dn1.set_next(dn2) #print(dn1.data) #print(dn1.next.data) #--reverse using stack #ostr = "Reverse" #print(reverse_string(ostr)) #---sort #usorted=[0,3,7,-5,8,1,-3,100] usorted=[100, 8 ,7 ,-5, 3, 1, -3] print('before sort ' ) print (usorted) s = sort.Sort(usorted) #---bubble sort #bubble_sort(usorted) sortd = s.merge_sort_loop(usorted) print('Merge sort done in %d loops.. Sorted Array '% (s.get_counter()) ) print (sortd) #x=-5 #print(binary_search(x,usorted)) #print(interpolation_search(x,usorted))
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy. Accept Learn more