Quick Sort

Given an array of integers, sort the elements in the array in ascending order. The quick sort algorithm should be used to solve this problem.

Examples

  • {1} is sorted to {1}
  • {1, 2, 3} is sorted to {1, 2, 3}
  • {3, 2, 1} is sorted to {1, 2, 3}
  • {4, 2, -3, 6, 1} is sorted to {-3, 1, 2, 4, 6}

Corner Cases

  • What if the given array is null? In this case, we do not need to do anything.
  • What if the given array is of length zero? In this case, we do not need to do anything.

Time Complexity: O(NlogN), worst case O(N^2)

Space Complexity: O(N)

 1 class Solution(object):
 2   def quickSort(self, array):
 3     """
 4     input: int[] array
 5     return: int[]
 6     """
 7     # write your solution here
 8     if array is None or len(array) <= 1:
 9       return array
10     self.helper(array, 0, len(array) - 1)
11     return array
12     
13   def helper(self, array, left, right):
14     if left >= right:
15       return
16     num = self.partition(array, left, right)
17     self.helper(array, left, num - 1)
18     self.helper(array, num + 1, right)
19 
20   def partition(self, array, left, right):
21     import random
22     rand = random.randint(left, right)
23     pivot = array[rand]
24     array[rand], array[right] = array[right], array[rand]
25     right_bound = right - 1
26     while left <= right_bound:
27       if array[left] <= pivot:
28         left += 1
29       elif array[right_bound] >= pivot:
30         right_bound -= 1
31       else:
32         array[left], array[right_bound] = array[right_bound], array[left]
33         left += 1
34         right_bound -= 1
35     array[right], array[left] = array[left], array[right]
36     return left

 

posted @ 2019-09-22 07:00  xuan_abc  阅读(115)  评论(0编辑  收藏  举报