Problem Introduction

The goal in this problem is to redesign a given implementation of the randomized quick sort algorithm so that it works fast even on sequences containing many equal elements.

Problem Description

Task.To force the given implementation of the quick sort algorithm to efficiently process sequences with few unique elements, your goal is replace 2-way partition with a 3-way partition. That is, your new partition procedure should partition the array into three parts: \(<x\) part, \(=x\) part, and \(>x\) part.

Input Format.The first line of the input contains an integer \(n\). The next line contains a sequence of \(n\) integers \(a_0, a_1, \cdots, a_{n-1}\).

Constraints.\(1 \leq n \leq 10^5; 1 \leq a_i \leq 10^9\) for all \(0 \leq i \leq n\).

Output Format.Output this sequence sorted in non-decreasing order.

Sample 1.
Input:

5
2 3 9 2 2

Output:

2 2 2 3 9

Solution

# Uses python3
import sys
import random

def partition3(a, l, r):
    x = a[l]
    m1, m2 = l, r
    i = l+1
    while i <= m2:
        if a[i] < x:
            a[i], a[m1] = a[m1], a[i]
            m1 += 1
            i += 1
        elif a[i] > x:
            a[i], a[m2] = a[m2], a[i]
            m2 -= 1
        else:
            i += 1
    return m1, m2

def partition2(a, l, r):
    x = a[l]
    j = l
    for i in range(l + 1, r + 1):
        if a[i] <= x:
            j += 1
            a[i], a[j] = a[j], a[i]
    a[l], a[j] = a[j], a[l]
    return j

def randomized_quick_sort(a, l, r):
    if l >= r:
        return
    k = random.randint(l, r)
    a[l], a[k] = a[k], a[l]
    #use partition3
    m1, m2 = partition3(a, l, r)
    randomized_quick_sort(a, l, m1 - 1);
    randomized_quick_sort(a, m2 + 1, r);

if __name__ == '__main__':
    input = sys.stdin.read()
    n, *a = list(map(int, input.split()))
    randomized_quick_sort(a, 0, n - 1)
    for x in a:
        print(x, end=' ')

[UCSD白板题] Sorting: 3-Way Partition的更多相关文章

  1. [UCSD白板题] Longest Common Subsequence of Three Sequences

    Problem Introduction In this problem, your goal is to compute the length of a longest common subsequ ...

  2. [UCSD白板题] Maximize the Value of an Arithmetic Expression

    Problem Introduction In the problem, your goal is to add parentheses to a given arithmetic expressio ...

  3. [UCSD白板题] Compute the Edit Distance Between Two Strings

    Problem Introduction The edit distinct between two strings is the minimum number of insertions, dele ...

  4. [UCSD白板题] Take as Much Gold as Possible

    Problem Introduction This problem is about implementing an algorithm for the knapsack without repeti ...

  5. [UCSD白板题] Primitive Calculator

    Problem Introduction You are given a primitive calculator that can perform the following three opera ...

  6. [UCSD白板题] Points and Segments

    Problem Introduction The goal in this problem is given a set of segments on a line and a set of poin ...

  7. [UCSD白板题] Number of Inversions

    Problem Introduction An inversion of a sequence \(a_0,a_1,\cdots,a_{n-1}\) is a pair of indices \(0 ...

  8. [UCSD白板题] Majority Element

    Problem Introduction An element of a sequence of length \(n\) is called a majority element if it app ...

  9. [UCSD白板题] Binary Search

    Problem Introduction In this problem, you will implemented the binary search algorithm that allows s ...

随机推荐

  1. Linux QT

    Check system version 1.  cat /proc/version mike@sp-ThinkPad-X220:~$ cat /proc/versionLinux version 3 ...

  2. tcp转发

    Proxy.java package com.dc.tcp.proxy; import java.io.IOException; import java.net.ServerSocket; impor ...

  3. 如何解救在异步Java代码中已检测的异常

    Java语言通过已检测异常语法所提供的静态异常检测功能非常实用,通过它程序开发人员可以用很便捷的方式表达复杂的程序流程. 实际上,如果某个函数预期将返回某种类型的数据,通过已检测异常,很容易就可以扩展 ...

  4. jquery实现动态添加html代码

    先看下思导图,整体了解下,然后我们再来学习. 现在我们来看一下几段代码,然后根据这几段代码我们来学习一下如何正确的学习动态添加html. 一.html()方法 html函数的作用原理首先是移除目标元素 ...

  5. PTA Sort Three Distinct Keys

    Suppose you have an array of N elements, containing three distinct keys, "true", "fal ...

  6. js Function.call

      提到上述的概念之前,首先想说说javascript中函数的隐含参数:arguments Arguments 该对象代表正在执行的函数和调用它的函数的参数. [function.]arguments ...

  7. AJAX同步改异步

    var temp; $.ajax({ async: false, type : "POST", url : defaultPostData.url, dataType : 'jso ...

  8. websocket实例(显示文件导入处理进度)

    大批量数据导入时,需要即时显示对文件的处理进度.考虑ajax轮询太浪费资源,使用websocket实现. 项目使用Spring MVC(3.1),与websocket结合要求版本4.0以上.所以没有使 ...

  9. css 清除浮动最佳方法!

    .clear:after{content:'\0020';display:block;height:0;clear:both} .clear{*zoom:1}

  10. 根据UIColor对象,获取对应的RGBA值

    - (NSArray *)getRGBWithColor:(UIColor *)color { CGFloat red = 0.0; CGFloat green = 0.0; CGFloat blue ...