| from Algorithm import Algorithm␍␊ |
| ␍␊ |
| class SortAlgorithm(Algorithm):␍␊ |
| # virtual void Sort␍␊ |
| ␍␊ |
| def Sort(self):␍␊ |
| raise Exception("Not implemented!")␍␊ |
| ␍␊ |
| class QuickSort(SortAlgorithm):␍␊ |
| ␍␊ |
| def Sort(self):␍␊ |
| self.quicksort(0, len(self._container) - 1)␍␊ |
| ␍␊ |
| ␍␊ |
| def quicksort(self, left, right):␍␊ |
| if right <= left:␍␊ |
| return;␍␊ |
| ␍␊ |
| store = 0␍␊ |
| pivotindex = left + right / 2␍␊ |
| self._container[pivotindex], self._container[right] = self._container[right], self._container[pivotindex]␍␊ |
| store = left␍␊ |
| for i in range(left, right):␍␊ |
| if self._container[i] <= self._container[right]:␍␊ |
| self._container[i], self._container[store] = self._container[store], self._container[i]␍␊ |
| store += 1␍␊ |
| ␍␊ |
| self._container[store], self._container[right] = self._container[right], self._container[store]␍␊ |
| self.quicksort(left, store - 1)␍␊ |
| self.quicksort(store + 1, right)␍␊ |
| ␍␊ |
| class MergeSort(SortAlgorithm):␍␊ |
| ␍␊ |
| def Sort(self):␍␊ |
| self._container = self.mergesort(self._container)␍␊ |
| ␍␊ |
| def mergesort(self, arr):␍␊ |
| if len(arr) <= 1:␍␊ |
| return arr␍␊ |
| ␍␊ |
| middle = len(arr) / 2␍␊ |
| left = arr[0:middle]␍␊ |
| right = arr[middle:]␍␊ |
| ␍␊ |
| left = self.mergesort(left)␍␊ |
| right = self.mergesort(right)␍␊ |
| ␍␊ |
| return self.merge(left, right)␍␊ |
| ␍␊ |
| def merge(self, left, right):␍␊ |
| res = []␍␊ |
| ␍␊ |
| while len(left) > 0 or len(right) > 0:␍␊ |
| if len(left) > 0 and len(right) > 0:␍␊ |
| if left[0] <= right[0]:␍␊ |
| res.append(left[0])␍␊ |
| left = left[1:]␍␊ |
| else:␍␊ |
| res.append(right[0])␍␊ |
| right = right[1:]␍␊ |
| elif len(left) > 0:␍␊ |
| res.append(left[0])␍␊ |
| left = left[1:]␍␊ |
| elif len(right) > 0:␍␊ |
| res.append(right[0])␍␊ |
| right = right[1:]␍␊ |
| ␍␊ |
| return res |