QuickSort1 - Partition

The previous challenges covered Insertion Sort, which is a simple and intuitive sorting algorithm. Insertion Sort has a running time of O(N2) which isn’t fast enough for most purposes. Instead, sorting in the real-world is done with faster algorithms like Quicksort, which will be covered in the challenges that follow.

The first step of Quicksort is to partition an array into two smaller arrays.

Challenge
You’re given an array ar and a number p. Partition the array, so that, all elements greater than p are to its right, and all elements smaller than p are to its left.

In the new sub-array, the relative positioning of elements should remain the same, i.e., if n1 was before n2 in the original array, it must remain before it in the sub-array. The only situation where this does not hold good is when p lies between n1and n2

i.e., n1 > p > n2.

Guideline - In this challenge, you do not need to move around the numbers ‘in-place’. This means you can create 2 lists and combine them at the end.

Input Format
You will be given an array of integers. The number p is the first element in ar.

There are 2 lines of input:

  • n - the number of elements in the array ar
  • the n elements of ar (including p at the beginning)

Output Format
Print out the numbers of the partitioned array on one line.

Constraints
1<=n<=1000 
-1000<=x<= 1000 , x ∈ ar 
All elements will be distinct

Sample Input
5
4 5 3 7 2

Sample Output
3 2 4 5 7


def partition(ar): 
    l=[]
    r=[]
    for x in ar:
        if x<ar[0]:
            l.append(x)
            
        if x>ar[0]:
            r.append(x)
    l.append(ar[0])
    l.extend(r)
       
    return " ".join(map(str,l))

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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值