Moved Python MergeSort & QucikSort to relevant ALGOL101 subfolders. #7

Merged
merged 2 commits into from Apr 5, 2012
@@ -0,0 +1,40 @@
+#TopDownMergeSortInPython:
+#A Python implementation of the pseudocode at
+#http://en.wikipedia.org/wiki/Merge_sort
+
+
+def merge_sort(m):
+ if len(m) <=1:
+ return m
+ left = []
+ right = []
+ middle = int(len(m) / 2)
+ for x in range(0, middle):
+ left.append(m[x])
+ for x in range(middle, len(m)):
+ right.append(m[x])
+ left = merge_sort(left)
+ right = merge_sort(right)
+ return merge(left, right)
+
+def merge(left, right):
+ result = []
+ while len(left) > 0 or len(right) > 0:
+ if len(left) > 0 and len(right) > 0:
+ if left[0] <= right[0]:
+ result.append(left[0])
+ left = left[1:len(left)]
+ else:
+ result.append(right[0])
+ right = right[1:len(right)]
+ elif len(left) > 0:
+ result.append(left[0])
+ left = left[1:len(left)]
+ elif len(right) > 0:
+ result.append(right[0])
+ right = right[1:len(right)]
+ return result
+
+
+input = [5, 4, 7, 8, 2, 3, 1, 6, 9]
+print merge_sort(input)
@@ -0,0 +1,42 @@
+__author__ = 'mike_selender'
+
+import random
+
+#Adapted from pseudocode at http://en.wikipedia.org/wiki/Quick_sort
+#left is the index of the leftmost element of the array
+#right is the index of the rightmost element of the array (inclusive)
+#number of elements in subarray = right-left+1
+
+def swap_array(input,x, y):
+ hold = input[x]
+ input[x] = input[y]
+ input[y] = hold
+
+def partition(input, leftIndex, rightIndex, pivotIndex):
+
+ pivotValue = input[pivotIndex]
+ swap_array(input, pivotIndex, rightIndex)
+ storeIndex = leftIndex
+ for i in range(leftIndex, rightIndex):
+ if input[i] < pivotValue:
+ swap_array(input, i, storeIndex)
+ storeIndex += 1
+ swap_array(input, storeIndex, rightIndex)
+ return storeIndex
+
+def QuickSort(input, leftIndex, rightIndex):
+
+ if leftIndex < rightIndex:
+ pivotIndex = random.randrange(leftIndex, rightIndex)
+ pivotNewIndex = partition(input, leftIndex, rightIndex, pivotIndex)
+ QuickSort(input, leftIndex, pivotNewIndex - 1)
+ QuickSort(input, (pivotNewIndex + 1), rightIndex)
+
+#input = [3, 8, 2, 10]
+input = [5, 4, 7, 8, 2, 3, 1, 6, 9]
+#print partition(input, 0, len(input) - 1, 1)
+QuickSort(input, 0, len(input) - 1)
+print input
+
+
+
@@ -1 +0,0 @@
-TopDownMergeSortInPython: A Python implementation of the pseudocode at http://en.wikipedia.org/wiki/Merge_sort