def NetherLandsFlag(nums, a): if not nums or len(nums) < 2: return nums ple = -1 pri = len(nums) # for i in range(len(nums)): # if nums[i] < a: # utils.swap(nums, i, ple + 1) # ple += 1 # for j in range(len(nums) - 1, -1, -1): # if nums[j] > a: # utils.swap(nums, j, pri - 1) # pri -= 1 i = 0 while i < pri: if nums[i] < a: utils.swap(nums, i, ple + 1) ple += 1 i += 1 elif nums[i] > a: utils.swap(nums, i, pri - 1) pri -= 1 else: i += 1 return nums
def bubbleSort(nums): if not nums or len(nums) < 2: return for k in range(len(nums), 0, -1): for i in range(k - 1): if nums[i] > nums[i + 1]: utils.swap(nums, i, i + 1) return
def sortArray(nums, num): if not nums or len(nums) < 2: return nums p = -1 for i in range(len(nums)): if nums[i] <= num: utils.swap(nums, i, p + 1) p += 1 return nums
def selectionSort(nums): if not nums or len(nums) < 2: return for i in range(len(nums)): min_index = i for j in range(i + 1, len(nums)): min_index = j if nums[j] < nums[min_index] else min_index utils.swap(nums, i, min_index) return
def insertionSort(nums): if not nums or len(nums) < 2: return for i in range(1, len(nums)): for j in range(i - 1, -1, -1): if nums[j + 1] >= nums[j]: break utils.swap(nums, j, j + 1) return
def heapifyB(self, start, size): left = (start << 1) + 1 right = left + 1 while left < start + size: bigger = right if right < start + size and self.nums[right] > self.nums[left] else left bigger = bigger if self.nums[bigger] > self.nums[start] else start if bigger == start: break utils.swap(self.nums, bigger, start) start = bigger left = (start << 1) + 1 right = left + 1
def heapifyS(self, start, size): root = 0 left = (root << 1) + 1 right = left + 1 print(self.nums[start:start + size]) while left < size: smallind = right if right < size and self.nums[start + right] < self.nums[start + left] else left smallind = smallind if self.nums[start + smallind] < self.nums[start + root] else root if smallind == root: break utils.swap(self.nums, start + smallind, start + root) root = smallind left = (root << 1) + 1 right = left + 1
def quickSort(nums, l=-1, r=-1): if not nums or len(nums) < 2: return if l == -1 and r == -1: l = 0 r = len(nums) - 1 if l < r: index = random.randint(l, r) utils.swap(nums, index, r) p, q = _partition(nums, l, r) quickSort(nums, l, p) quickSort(nums, q, r)
def _partition(nums, l, r): pL = l - 1 pR = r i = l while i < pR: if nums[i] < nums[r]: utils.swap_xor(nums, i, pL + 1) pL += 1 i += 1 elif nums[i] > nums[r]: utils.swap_xor(nums, i, pR - 1) pR -= 1 else: i += 1 utils.swap(nums, pR, r) return pL, pR + 1