QuickSort

In the previous challenge, you wrote a partition method to split an array into 2 sub-arrays, one containing smaller elements and one containing larger elements. This means you ‘sorted’ half the array with respect to the other half. Can you repeatedly use partition to sort an entire array?

Guideline
In Insertion Sort, you simply went through each element in order and inserted it into a sorted sub-array. In this challenge, you cannot focus on one element at a time, but instead must deal with whole sub-arrays, with a strategy known as “divide and conquer”.

When partition is called on an array, two parts of the array get ‘sorted’ with respect to each other. If partition is then called on each sub-array, the array will now be split into 4 parts. This process can be repeated until the sub-arrays are small. Notice that when partition is called on just two numbers, they end up being sorted.

Can you repeatedly call partition so that the entire array ends up sorted?

Print Sub-Arrays
In this challenge, print your array every time your partitioning method finishes, i.e. print every sorted sub-array The first element in a sub-array should be used as a pivot. Partition the left side before partitioning the right side. The pivot should not be added to either side. Instead, put it back in the middle when combining the sub-arrays together.

Input Format
There will be two lines of input:

  • n - the size of the array
  • ar - the n numbers of the array

Output Format
Print every partitioned sub-array on a new line.

Constraints
1<=n<=1000 
-1000<=x<= 1000 , x ∈ ar
There are no duplicate numbers.

Sample Input

7
5 8 1 3 7 9 2

Sample Output
2 3 
1 2 3 
7 8 9 
1 2 3 5 7 8 9

Explanation
This is a diagram of QuickSort operating on the sample array:

quick-sort diagram

Task
The method quickSort takes in a parameter, ar, an unsorted array. Use the QuickSort Algorithm to sort the entire array.


def quickSort(ar):
    if len(ar) < 2:
        return(ar)
    else:
        p = ar[0]
        less = []
        more = []
        for item in ar[1:]:
            if item < p:
                less.append(item)
            else:
                more.append(item)
        
       # final = less if less else [] + [p] + more if more else []
        
        l = quickSort(less)
        m = quickSort(more)
        subarray = l+ [p] + m
        print(' '.join([str(x) for x in subarray]))
        return l + [p] +m


m = input()
ar = [int(i) for i in raw_input().strip().split()]
quickSort(ar)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值