zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    cookie 当天12点 过期
    ps 前端常用技巧
    定时器遇到的坑
    ajax 会遇到的问题总结
    立即执行函数表达式 项目经常用到js 代码Module模式
    Hello world
    div position:fixed后,水平居中的问题
    关于div中图片水平垂直居中的问题
    [学习]Activiti流程引擎 入门(1) 初步认识
    SSO框架介绍前篇
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11565801.html
Copyright © 2011-2022 走看看