Created
August 17, 2017 19:57
-
-
Save mortymacs/39dad1ea538940230ac8081db9600aaf to your computer and use it in GitHub Desktop.
Quick sort in Python
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
| #!/usr/bin/env python | |
| class QuickSort: | |
| """Quick sort implementation.""" | |
| def __init__(self, data): | |
| """Initialize array.""" | |
| self._array = data | |
| def partition(self, left, right): | |
| """Partitioning the array.""" | |
| pivot = right | |
| right = right - 1 | |
| while True: | |
| while self._array[left] < self._array[pivot]: | |
| left += 1 | |
| while self._array[right] > self._array[pivot]: | |
| right -= 1 | |
| if left >= right: | |
| break | |
| else: | |
| self._swap(left, right) | |
| self._swap(left, pivot) | |
| return left | |
| def sort(self, left, right): | |
| """Run quick sort action.""" | |
| if right - left <= 0: | |
| return | |
| pivot = self.partition(left, right) | |
| self.sort(left, pivot - 1) | |
| self.sort(pivot + 1, right) | |
| def _swap(self, left, right): | |
| """Swap left value with right value.""" | |
| self._array[left], self._array[right] = self._array[right], self._array[left] | |
| @property | |
| def array(self): | |
| """Return array content.""" | |
| return self._array | |
| # Run sample code | |
| if __name__ == "__main__": | |
| data = [0, 5, 2, 1, 6, 3] | |
| print("Before sorting:", data) | |
| action = QuickSort(data) | |
| action.sort(0, len(data) - 1) | |
| print("After sorting:", action.array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment