Repository where I mostly put random python scripts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.5 KiB

  1. # coding: utf-8
  2. # In[1]:
  3. #Merge Slot Without Slicing
  4. #start is the index of the first item
  5. #end is the index past the the last item
  6. def indexMergeSort(alist, start = None, end = None):
  7. if start == None:
  8. start = 0
  9. if end == None:
  10. end = len(alist)
  11. #note that the print operations still use slicing for convenience
  12. #print("Input: ",alist[start:end])
  13. length = end - start
  14. if length > 1:
  15. #print("Splitting ",alist[start:end])
  16. mid = start + length//2
  17. indexMergeSort(alist, start, mid)
  18. indexMergeSort(alist, mid, end)
  19. i=start # index for the left part of the list
  20. j=mid # index for the right part of the list
  21. #we use a temporary list
  22. templist = [None] * (length)
  23. k = 0 #index for the temp list
  24. while i < mid and j < end:
  25. if alist[i] < alist[j]:
  26. templist[k] = alist[i]
  27. i=i+1
  28. else:
  29. #we swap
  30. templist[k] = alist[j]
  31. j=j+1
  32. k=k+1
  33. while i < mid:
  34. templist[k] = alist[i]
  35. i=i+1
  36. k=k+1
  37. while j < end:
  38. templist[k]=alist[j]
  39. j=j+1
  40. k=k+1
  41. #we copy the results
  42. for k in range(length):
  43. alist[start+k] = templist[k]
  44. #print("Merging ",alist[start:mid], alist[mid:end])
  45. alist = [54,26,93,17,77,31,44,55,20]
  46. indexMergeSort(alist)
  47. print(alist)