对数字列表进行排序[关闭]


25

关于代码保龄球:

在高尔夫中,您尝试获得最低的分数(最小的应用程序,最优雅的应用程序等)。在保龄球中,您尝试获得最高分。因此,如果您遵循此规则,那么进行代码保龄球挑战的目标是使最大,最混搭,最难维护的代码片段仍然能够满足挑战的要求。但是,仅出于此目的而延长源代码是没有意义的。看起来增加的长度似乎来自设计,而不仅仅是填充。

挑战:

创建一个程序,以升序对数字列表进行排序。

例:

输入: 1,4,7,2,5

输出: 1,2,4,5,7

代码:显然,这不是一个好答案,因为那里没有很多WTF。

function doSort(array $input) {
    sort($input);
    return $input;
}

规则:

没有真正的规则。只要程序起作用,就可以了!

切记:这是保龄球,而不是高尔夫。目的是制作最糟糕,最混蛋的代码!看起来不错但实际上看似邪恶的代码的加分点...


我希望我仍然可以写一次日历队列代码...
Peter Taylor

14
sort(sort(sort(sort(sort(sort(myarray))))))保证完美的分类!
Mateen Ulhaq 2011年

Answers:


21

按用户输入排序。有什么会更糟?

function sort(array) {
    newArray = new Array
    notSorted = true;
    while (notSorted) {
        sortfail = false;
        i = -1
        for (;;) {
            if ((++i + 1) == array.length) break;
            if (confirm("is " + array[i] + " less than " + array[i + 1])) {
                newArray[i] = array[i]
                newArray[i + 1] = array[i + 1]
            } else {
                newArray[i] = array[i + 1]
                newArray[i + 1] = array[i]
                array[i] = newArray[i]
                array[i + 1] = newArray[i + 1]
                sortfail = true
            }
        }
        array = newArray;
        if (!sortfail) notSorted = false
    }
    return array
}

console.log(sort([2,1,3]))

查看现场示例


您可以做得更好……
-D

更好并且仍然正确排序?真痛苦 这在算法上是可怕的。我不需要使代码更可怕。
雷诺斯2011年

5
用户输入通常是错误的。用户可能喝醉了或喝醉了,也可能有对手故意给您错误的命令。应该随机洗牌,然后再问一次,直到您获得相同配对的相当数量的答案为止。
保罗

@Paul用户输入缺乏防御是此代码碗的主要优点之一。我猜想对用户输入进行完全无用的验证会比没有更好。
雷诺斯

对此的手动元素不确定。
史蒂夫·罗宾斯

16
class Array
  def sort
    self.permutation.min
  end
end

啊,Ruby的优雅……self.permutation产生了一个枚举器。尚未造成伤害。但是,看起来无辜的.min会将此枚举数吸引到一个数组中。当元素数量增加时,此数组的大小将爆炸。更不用说这破坏了一个很好的预先存在的种类。


2
如果您以前从未看过它,那么它就是代码保龄球 –您必须编写最长的代码!;)
nyuszika7h 2011年

3
我要的是“好看但看似邪恶的”奖金:)
steenslag 2011年

3
我想说,这对任何SQL程序员来说似乎都很好。现在,编译器只需要弄清楚您想要的只是一种简单的排序。
aaaaaaaaaaaaaa

15

Bogosort!

import random

def is_sorted(seq):
    for x, y in zip(seq[:-1], seq[1:]):
        if x > y:
            return False
    return True

def sort(seq):
    while not is_sorted(seq):
        random.shuffle(seq)

该死的你打败了我...
arrdem


效率:O(2n random)
Seequ 2015年

12

Perl气泡排序

push(@m,'0');$a=<>;push(@m,$a);
$a=pop@m;push(@c,$a);
push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
$a=pop@c;push(@c,$a);for(1..$a){$a=<>;push(@m,$a);
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
$a=pop@m;$b=pop@m;$hash{$a}=$b;
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;$b=pop@m;push(@m,$b+$a);
push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
}$a=pop@c;push(@m,$a);
push(@m,'2');$a=pop@m;$b=pop@m;for(1..$a){push(@m,$b);};
$a=pop@m;$b=pop@m;push(@m,$b*$a);
$a=pop@m;push(@c,$a);
$a=pop@c;push(@c,$a);for(1..$a){push(@m,'1');$a=pop@m;push(@m,-$a);
push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
$a=pop@c;push(@c,$a);for(1..$a){push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;$b=pop@m;push(@m,$b+$a);
push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
$a=pop@m;push(@m,$hash{$a});
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;push(@m,-$a);
$a=pop@m;$b=pop@m;push(@m,$b+$a);
$a=pop@m;push(@m,$hash{$a});
$a=pop@m;$b=pop@m;if($b < $a){push(@c,1)}else{push(@c,0)};
$a=pop@c;push(@c,$a);for(1..$a){push(@m,'p');$a=pop@m;push(@m,$hash{$a});
$a=pop@m;push(@m,$hash{$a});
push(@m,'t');$a=pop@m;$b=pop@m;$hash{$a}=$b;
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;push(@m,-$a);
$a=pop@m;$b=pop@m;push(@m,$b+$a);
$a=pop@m;push(@m,$hash{$a});
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
$a=pop@m;$b=pop@m;$hash{$a}=$b;
push(@m,'t');$a=pop@m;push(@m,$hash{$a});
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;push(@m,-$a);
$a=pop@m;$b=pop@m;push(@m,$b+$a);
$a=pop@m;$b=pop@m;$hash{$a}=$b;
}$a=pop@c;push(@m,$a);
$a=pop@m;
}}push(@m,'0');push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
$a=pop@c;push(@c,$a);for(1..$a){push(@m,'p');$a=pop@m;push(@m,$hash{$a});
$a=pop@m;push(@m,$hash{$a});
$a=pop@m;print$a;
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;$b=pop@m;push(@m,$b+$a);
push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
}

我一直在寻找“每条单线看起来都像同一条线噪音”的外观。输入的第一行(在STDIN上)告诉程序有多少个数字,而接下来的N个行包含一个需要排序的数字。


3
基于堆栈的perl :)
Daniel Gratzer 2012年

我想解释一下它是如何工作的?我有些猜测
Xavier Combelle

12

Java中的通用多线程bogosort

46秒排序4个数字

我认为支持泛型会很优雅。另外,多线程总是很不错的,所以我用它代替随机化:该程序为每个要排序的数字生成一个线程。每个线程都尝试将其元素插入数组对象,并且在插入所有元素后,程序将检查数组是否已排序。如果没有,请再试一次。当然,此插入需要同步。

元素插入器

这将是我们用于线程的类。此类包含一个元素并将其插入到其中sortedArray

class ElementInserter<E extends Comparable<? super E>> implements Runnable {
    E element;
    SortedArray<? super E> target;

    ElementInserter(E e, SortedArray<? super E> a) {
        element = e;
        target = a;
    }

    @Override
    public void run() {
        target.insert(element);
    }
}

sortedArray

采用直接插入方法。插入最后一个元素后,它将检查数组是否已排序。

class SortedArray<E extends Comparable<? super E>> {
    boolean sorted; int i = 0; E[] a;

    SortedArray(E[] e) { a = e; }

    synchronized public void insert(E e) {
        while (!sorted) {
            a[i++] = e;

            if (i == a.length) {
                sorted = true;

                for (int j = 1; j < i; ++j)
                    if (a[j-1].compareTo(a[j]) > 0) {
                        sorted = false;
                        i = 0;
                        notifyAll();
                    }

                if (sorted) {
                    for (int j = 0; j < a.length; ++j) System.out.print(a[j]+" ");
                    System.out.println();
                    notifyAll(); // allow all threads to terminate
                }

            } else
                try { wait(); }
                catch(InterruptedException x) { }
        }
    }
}

主要方法

将命令行参数解析为Integer,为每个Integer创建一个新数组和一个新线程:

    public static void main (String[] args) {
        Integer[] i = new Integer[args.length];
        SortedArray<Integer> c = new SortedArray<Integer>(i);

        for (String s : args)
            new Thread(new ElementInserter<Integer>(Integer.parseInt(s), c)).start();
    }

测试运行

执行时间将取决于元素的原始顺序和您的调度程序实现。这是在双核2.9 GHz Intel i7 MacBook Pro上:

$ time java Main 3 1 2 4
1 2 3 4 

real    0m46.307s
user    0m14.629s
sys     0m26.207s

1
哈哈+1我得到了
好处

10

JavaScript(带有动画!)。8172个字符。几个小时的6个数字。

我们喜欢彩票,对不对?类似于dan04的Bogosort,但使用物理和动画 ...

(function(){var e={},v=!1,G=/abc/.test(function(){abc})?/\b_super\b/:/.*/,H=function(c,a,b){return function(){var l=this._super,s;this._super=b[c];try{s=a.apply(this,arguments)}finally{this._super=l}return s}};e.Class=function(){};e.Class.extend=function a(b){var l=this.prototype;v=!0;var s=new this;v=!1;for(var c in b)s[c]="function"===typeof b[c]&&"function"===typeof l[c]&&G.test(b[c])?H(c,b[c],l):b[c];b=function(){!v&&this.init&&this.init.apply(this,arguments)};b.prototype=s;b.prototype.constructor=
b;b.extend=a;return b};e.Events={};var k=e.Events,z,A,w=Object.prototype.toString,I=document.createEvent,r=Date.now;k.EventListener=e.Class.extend({handleEvent:function(){},init:function(a){this.handleEvent=a}},"EventListener");z=k.EventListener;k.Event=e.Class.extend({timeStamp:0,type:"",target:null,cancelable:!1,defaultPrevented:!1,preventDefault:function(){this.cancelable&&(this.defaultPrevented=!0)},initEvent:function(a,b){this.type=a;this.target=b;this.timeStamp=r()}},"Event");A=k.Event;var t=
Object.create(null);e.createEventType=function(a,b){t[a]=A.extend(b,a);return t[a]};e.createEvent=function(a){return null!=t[a]?(a=new t[a],a.timeStamp=r(),a):I(a)};k.EventTarget=e.Class.extend({_listeners:{},addEventListener:function(a,b,l){var c=this._listeners[a];if(!(null!=c&&function(){for(var a="object"===typeof l?l:null,d,e=0,f=c.length;e<f;e++)if(d=this.listeners[e],d.listener.handleEvent===b&&d.scope===a)return!0;return!1}())){var d={listener:"object"===typeof b&&b.handleEvent?b:new z(b),
scope:"object"===typeof l?l:null};"[object Array]"===w.call(c)?c.push(d):this._listeners[a]=[d]}},removeEventListener:function(a,b,c){a=this._listeners[a];if("[object Array]"===w.call(a)){c="object"===typeof c?c:null;for(var d=0,e=a.length;d<e;d++)if(a[d].listener.handleEvent===b&&a[d].scope===c){a.splice(d,1);break}}},dispatchEvent:function(a){a.target||(a.target=this);var b=0,c=this._listeners[a.type],d=c.length,e;if("[object Array]"===w.call(c))for(;b<d;b++)e=c[b].listener.handleEvent,e.call(c[b].scope,
a);return a.defaultPrevented}},"EventTarget");for(var B=0,k=["ms","moz","webkit","o"],h=0;h<k.length&&!window.requestAnimationFrame;++h)window.requestAnimationFrame=window[k[h]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[k[h]+"CancelAnimationFrame"]||window[k[h]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(a){var b=r(),c=Math.max(0,16-(b-B)),d=window.setTimeout(function(){a(b+c)},c);B=b+c;return d});window.cancelAnimationFrame||
(window.cancelAnimationFrame=function(a){clearTimeout(a)});var x=window.clearInterval,C=window.setInterval,D=e.Class.extend({fn:function(){},args:[],thisArg:window,sleepTime:0,init:function(a,b,c){this.method=a||function(){};this.thisArg=b||window;this.args=c||[]}},"FunctionToCall"),r=Date.now,u=Object.create(null);u.animation=0;u.steady=1;u.as_fast_as_possible=2;e.Timer=e.Events.EventTarget.extend({ANIMATION:0,STEADY:1,AS_FAST_AS_POSSIBLE:2,TimerEvent:e.createEventType("TimerEvent",{FPS:0,targetFPS:0,
delta:0,initEvent:function(a,b){if(null==b.getFPS||null==b.targetFPS||null==b.dt)throw notATimerException;this.FPS=b.getFPS();this.targetFPS=b.targetFPS;this.delta=b.dt;this._super(a,b)}}),_clearIntervalFlag:!1,_recursionCounter:0,_tickHandlersFromMethod:Object.create(null),running:!1,paused:!1,mode:0,autoStartStop:!0,setAutoStartStop:function(a){this.autoStartStop=a},prevTime:0,dt:0,maxDelta:0.05,setMaxDelta:function(a){this.maxDelta=a},sysTimerId:-1,targetFPS:50,setFPS:function(a){this.targetFPS=
a;if(this.running&&this.mode===this.STEADY){x(this.sysTimerId);var b=this;this.sysTimerId=C(function(){b.tick()},1E3/a)}},getFPS:function(){return 1/this.dt},queue:[],addToQueue:function(a,b,c){var d=new D(a,b,c),e;this.queue.push(d);var f=function J(f){0<d.sleepTime?d.sleepTime-=f.delta:(e=a.apply(b,[f].concat(c)),"number"===typeof e&&0<e?d.sleepTime=e:!0!==e&&(this.removeEventListener("tick",J,this),this.queue.splice(this.queue.indexOf(d),1)))};null==this._tickHandlersFromMethod[a]?this._tickHandlersFromMethod[a]=
[f]:this._tickHandlersFromMethod[a].push(f);this.addEventListener("tick",f,this);this.autoStartStop&&!this.running&&this.startLoop()},removeFromQueue:function(a){var b=this._tickHandlersFromMethod[a];a=this.queue.indexOf(a);if(-1!==a){for(var c=0,d=b.length;c<d;c++)this.removeEventListener("tick",b[c],this);return this.queue.splice(a,1)}},getQueue:function(){return this.queue.slice(0)},pause:function(){this._clearIntervalFlag=this.paused=!0;this.dt=0},resume:function(){this.paused=!1;this.startLoop()},
startLoop:function(){this.prevTime=r();this.running=!0;if(this.mode===this.steady){var a=this;this.sysTimerId=C(function(){a.tick()},1E3/this.targetFPS)}else this.tick()},tick:function(){if(this._clearIntervalFlag&&-1!==this.sysTimer)x(this.sysTimerId),this.sysTimerId=-1,this._clearIntervalFlag=!1;else if(!this.paused){var a=r();this.dt=(a-this.prevTime)/1E3;this.dt>this.maxDelta&&(this.dt=this.maxDelta);if(0===this.dt&&4>this._recursionCounter)this._recursionCounter++,this.tick();else{0<this._recursionCounter&&
(this._recursionCounter=0);var b=e.createEvent("TimerEvent");b.initEvent("tick",this);this.dispatchEvent(b);this.prevTime=a;a=!(this.autoStartStop&&0>=this.queue.length);if(this.mode===this.AS_FAST_AS_POSSIBLE&&a){var c=this;setTimeout(function(){c.tick()},0)}if(this.mode===this.ANIMATION&&a){var d=this;requestAnimationFrame(function(){d.tick()})}a||(this.running=!1,this.mode===this.STEADY&&-1!==this.sysTimerId&&(x(this.sysTimerId),this.sysTimerId=-1))}}},init:function(a){this.mode="number"===typeof a?
a:u[a];if(null==this.mode||0>this.mode||2<this.mode)this.mode=0}},"Timer");e.Timer.ANIMATION=0;e.Timer.STEADY=1;e.Timer.AS_FAST_AS_POSSIBLE=2;e.Timer.FunctionToCall=D;var j=[2,3,5,8,4,6],m=new (e.Class.extend({displace:0,velocity:0,drag:0.01,tickInterval:10,update:function(a){this.displace+=this.velocity*a.delta;this.velocity*=1-this.drag},init:function(){}})),q=j.slice(0),k=new e.Timer(0),h=document.createElement("div");h.style.width=23*j.length-28+"px";h.style.height="22px";h.style.overflowX="hidden";
h.style.overflowY="hidden";h.style.border="1px #555 solid";h.style.fontFamily='Consolas, "Courier New"';for(var c=[],f=0;f<j.length;f++)c[f]=document.createElement("div"),c[f].style.width="20px",c[f].style.height="20px",c[f].style.display="inline-block",c[f].style.position="relative",c[f].style.left=f+1===j.length?"-22px":"0px",c[f].style.top=f+1===j.length?"-22px":"0px",c[f].style.border="1px #AAA solid",c[f].style.textAlign="center",c[f].innerHTML=j[f],h.appendChild(c[f]);var g=0,d=1,n,p,E=0,F=
0,y=0;m.velocity=1E3*Math.random()+500;document.getElementsByTagName("body")[0].appendChild(h);k.addToQueue(function(a){if(5>m.velocity)if(0===g){for(a=0;a<c.length;a++)if((m.displace+22+22*a)%(22*j.length)-22<11*c.length&&(m.displace+22+22*a)%(22*j.length)>11*c.length){n=c[a];E=parseFloat(n.style.left);break}for(a=0;a<c.length;a++)if((m.displace+22+22*a)%(22*j.length)<11*c.length&&(m.displace+22+22*a)%(22*j.length)+22>11*c.length){p=c[a];F=parseFloat(p.style.left);break}y=p.offsetLeft-n.offsetLeft;
g=1}else if(1===g)n.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",p.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",d-=10*a.delta,0>d&&(g=2);else if(2==g)n.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",p.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",d+=10*a.delta,1<d&&(g=3,n.style.backgroundColor="rgba(255,255,255,0)",p.style.backgroundColor="rgba(255,255,255,0)",d=0);else if(3==g)n.style.left=E+d*y+"px",p.style.left=F-d*y+"px",d+=2*a.delta,1<
d&&(g=4);else if(4==g){if(d-=a.delta,0.5>d){a=c.indexOf(n);var b=c.indexOf(p),e;e=n.innerHTML;c[a].innerHTML=p.innerHTML;c[b].innerHTML=e;e=q[a];q.splice(a,1,q[b]);q.splice(b,1,e);b=-1/0;for(a=0;a<q.length;a++){if(q[a]<b){g=5;break}b=q[a]}g=5===g?5:6}}else if(5===g)d=1,m.velocity=1E3*Math.random()+500,g=0;else{if(6===g)return d=1,g=0,document.getElementsByTagName("body")[0].innerHTML+=q,!1}else{m.update(a);for(a=0;a<c.length;a++)b=(m.displace+22+22*a)%(22*j.length),a+1===j.length&&(b+=22*(j.length-
1)),c[a].style.left=b-22*a-22+"px"}return!0})})();​

但是,我使用了一些Google Closure Compiler来...等等,我不知道。但是看起来很丑,对吧?

这就像是一个彩票轮,每次停止时都会交换到中间的数字。您可以在此处播放:http : //jsfiddle.net/VkJUE/5/(以了解我的意思)

它确实可以工作,但是6个数字可能要花费几个小时。但是,我测试了3个数字,效果很好!


7

尽管我无法赞扬此Java代码,但是Smoothsort是可读性和性能之间折衷的一个很好的例子:

static final int LP[] = { 1, 1, 3, 5, 9, 15, 25, 41, 67, 109,
  177, 287, 465, 753, 1219, 1973, 3193, 5167, 8361, 13529, 21891,
  35421, 57313, 92735, 150049, 242785, 392835, 635621, 1028457,
  1664079, 2692537, 4356617, 7049155, 11405773, 18454929, 29860703,
  48315633, 78176337, 126491971, 204668309, 331160281, 535828591,
  866988873 // the next number is > 31 bits.
};

public static <C extends Comparable<? super C>> void sort(C[] m,
    int lo, int hi) {
  int head = lo; // the offset of the first element of the prefix into m

  int p = 1; // the bitmap of the current standard concatenation >> pshift
  int pshift = 1;

  while (head < hi) {
    if ((p & 3) == 3) {
      sift(m, pshift, head);
      p >>>= 2;
      pshift += 2;
    } else {
      // adding a new block of length 1
      if (LP[pshift - 1] >= hi - head) {
        // this block is its final size.
        trinkle(m, p, pshift, head, false);
      } else {
        // this block will get merged. Just make it trusty.
        sift(m, pshift, head);
      }

      if (pshift == 1) {
        // LP[1] is being used, so we add use LP[0]
        p <<= 1;
        pshift--;
      } else {
        // shift out to position 1, add LP[1]
        p <<= (pshift - 1);
        pshift = 1;
      }
    }
    p |= 1;
    head++;
  }

  trinkle(m, p, pshift, head, false);

  while (pshift != 1 || p != 1) {
    if (pshift <= 1) {
      // block of length 1. No fiddling needed
      int trail = Integer.numberOfTrailingZeros(p & ~1);
      p >>>= trail;
      pshift += trail;
    } else {
      p <<= 2;
      p ^= 7;
      pshift -= 2;

      trinkle(m, p >>> 1, pshift + 1, head - LP[pshift] - 1, true);
      trinkle(m, p, pshift, head - 1, true);
    }

    head--;
  }
}

private static <C extends Comparable<? super C>> void sift(C[] m, int pshift,
    int head) {   
  C val = m[head];

  while (pshift > 1) {
    int rt = head - 1;
    int lf = head - 1 - LP[pshift - 2];

    if (val.compareTo(m[lf]) >= 0 && val.compareTo(m[rt]) >= 0)
      break;
    if (m[lf].compareTo(m[rt]) >= 0) {
      m[head] = m[lf];
      head = lf;
      pshift -= 1;
    } else {
      m[head] = m[rt];
      head = rt;
      pshift -= 2;
    }
  }  

  m[head] = val;
}

private static <C extends Comparable<? super C>> void trinkle(C[] m, int p,
    int pshift, int head, boolean isTrusty) {

  C val = m[head];

  while (p != 1) {
    int stepson = head - LP[pshift];

    if (m[stepson].compareTo(val) <= 0)
      break; // current node is greater than head. Sift.

    if (!isTrusty && pshift > 1) {
      int rt = head - 1;
      int lf = head - 1 - LP[pshift - 2];
      if (m[rt].compareTo(m[stepson]) >= 0
          || m[lf].compareTo(m[stepson]) >= 0)
        break;
    }

    m[head] = m[stepson];

    head = stepson;
    int trail = Integer.numberOfTrailingZeros(p & ~1);
    p >>>= trail;
    pshift += trail;
    isTrusty = false;
  }

  if (!isTrusty) {
    m[head] = val;
    sift(m, pshift, head);
  }
}

/* insert some basic static void main here... 
   my Java's too rusty to do it from the top of my head 
*/

(注意:为了使效果更短一些而删除了一些注释;摘录自上面链接的维基百科页面)


您可以在帖子中添加您使用的语言吗?
内森·奥斯曼

“在可读性和性能之间进行权衡” —我需要记住这一点。
FUZxxl 2015年

7

F# “我恨函数式编程”:

let numbers = System.Console.ReadLine().Split(',')
let mutable check = 0
let mutable sorted = ""

while not (sorted.Split(',').Length = numbers.Length) do
    for i in [check..check + 1000] do
        for number in numbers do
            if number = i.ToString() then
                if sorted.Length > 0 then
                    sorted <- sorted + "," 
                sorted <- sorted + number
    check <- check + 1000

printfn "%s" sorted

7

Ruby Metasort

#I know Ruby has a built-in method to order an array,
#but I can't remember what it is.  Oh well, metaprogramming to the rescue!
#I'll just try all of the available methods, and see which one works.

#check whether an array is ordered
def is_in_order? arr
  arr.is_a?(Array) && (0...(arr.size-1)).all? {|i| arr[i]<arr[i+1]}
end

Array.instance_methods.each do |meth|
  begin
    possibly_ordered_array = ARGV.map(&:to_i).send(meth)
    #have to check both that the new array is ordered, and that it's still the same size,
    #so that methods that change the array's elements don't create false positives.
    if is_in_order?(possibly_ordered_array) && possibly_ordered_array.size == ARGV.size
      puts possibly_ordered_array.join(", ")
      exit 0 #success!
    end
  rescue
    #method needed an argument or something
  end
end

exit 1 #could not order the array

6

一个Cobol子程序,用于对整数表进行排序,保证其WTF /分钟比任何其他语言都高。为了提高性能,使用了QuickSort算法:

Identification Division.                                        
Program-ID. QwikSort is recursive.                              
Environment Division.                                           
Data Division.                                                  
Working-Storage Section.                                        
01 QwikSort-Working-Storage.                                    
 05 Swap-Space           Pic X(80) Value spaces.               
 05 Pivot         Binary Pic S9(8).                            
 05 I             Binary Pic S9(8).                            

Local-Storage Section.                                          
01 QwikSort-Local-Storage.                                      
 05 Lo            Binary Pic S9(8) Value 0.                    
 05 Hi            Binary Pic S9(8) Value 0.                    

Linkage Section.                                                

01 The-Table-Area.                                              
 05 The-Table     occurs 0 to 200000 depending on High-Element.
  10 The-Key     Binary Pic S9(8).                            

01 Low-Element     Binary Pic S9(8).                            
01 High-Element    Binary Pic S9(8).                            

Procedure Division using The-Table-Area                         
                         Low-Element                            
                         High-Element.                          

  Compute Lo  = Low-Element                                   
  Compute Hi  = High-Element                                  

  If ( High-Element > Low-Element )                           
     Perform Select-Pivot          

* ----- Loop through table until indices cross                   
       Perform until Hi < Lo                                    

* -------- Locate an item that should not be in less partition    
          Perform varying Lo from Lo by 1                        
            until (( Lo >= High-Element )                        
               or  ( The-Key of The-Table ( Lo ) >= Pivot ))     
          End-Perform                                            


* -------- Locate an item that should not be in greater partition 
          Perform varying Hi from Hi by -1                       
            until (( Hi <= Low-Element )                         
               or  ( The-Key of The-Table ( Hi ) <= Pivot ))     
          End-Perform                                            

* -------- Exchange the two and keep looking                      
          If ( Lo <= Hi )                                        
             Perform Swap-Elements                               
             Compute Lo = Lo + 1                                 
             Compute Hi = Hi - 1                                 
          End-If                                                 

    End-Perform                                               

    Perform Qsort-Less-Partition                              

    Perform Qsort-Greater-Partition                           

 End-If                                                       

 Goback.                                                      

*--------------------------------------------------------------*  
* Select the pivot using median of three rule.                    
*--------------------------------------------------------------*  
 Select-Pivot.                                                    

    Compute Pivot = ( Lo + Hi ) / 2                              
    Compute Pivot = Function Median (                            
            The-Key of The-Table ( Lo )                          
            The-Key of The-Table ( Pivot )                       
            The-Key of The-Table ( Hi )                          
         )                                                       
    End-Compute                                                  

    Exit.                                                        

*--------------------------------------------------------------*  
* Exchange elements in the wrong partition                        
*--------------------------------------------------------------*  
 Swap-Elements.                                                   
    Move The-Table ( Lo ) to Swap-Space                          
    Move The-Table ( Hi ) to The-Table ( Lo )                    
    Move Swap-Space       to The-Table ( Hi )                    
    Exit.                   

*--------------------------------------------------------------*  
* Sort the less sub-partition                                     
*  -- Optimization opportunity for the user: if the partition     
*    size is sufficiently small you might want to apply a simple  
*    sort like insertion or bubble, or perhaps a bose-nelson      
*    network to order the last few and save the overhead of       
*    another recursive call.                                      
*--------------------------------------------------------------*  
 Qsort-Less-Partition.                                            
    If ( Low-Element < Hi )                                      
       Call 'QwikSort' Using                                     
          The-Table-Area                                         
          Low-Element                                            
          Hi                                                     
       End-Call                                                  
    End-If 
    Exit.                                                        

*--------------------------------------------------------------*  
* Sort the greater sub-partition                                  
*  -- Optimization opportunity for the user: same as left part.   
*--------------------------------------------------------------*  
 Qsort-Greater-Partition.                                         
    If ( Lo < High-Element )                                     
       Call 'QwikSort' Using                                     
          The-Table-Area                                         
          Lo                                                     
          High-Element                                           
       End-Call                                                  
    End-If                              
    Exit.                                                        

 End Program QwikSort.

有什么理由QwikSort代替它QuickSort吗?(即长度限制还是您不能在名称中使用字母u?)因为那样会使它变得更加有趣:P
marinus 2012年

@marinus可能是链接器限制。
Craig Trader 2014年


它是“ QwikSort”而不是“ QuickSort”,以适应早期操作系统对事物施加的八个字符长度限制。“ QwikSort”可以很好地适合MVS PDS或旧式DOS计算机。
Joe Zitzelberger

不需要大写字母,Cobol的小写字母也很好,我很高兴打保龄球,但请
记住

4
var inp = [1, 4, 7, 2, 5],
    loops = 0,
    trysort;

while(++loops) {
    trysort = new Array(inp.length);

    for(var i = 0, len = inp.length; i < len; i++) {
        trysort[i] = inp[~~(Math.random()*inp.length)];
    }

    if( trysort.join(',') === '1,2,4,5,7' )
        break;
}
alert('done! Only ' + loops + ' iterations! ' + trysort);

http://www.jsfiddle.net/sAFMC/


在数组tut tut中进行了硬编码。
雷诺斯


很好 我喜欢。
Vaibhav'2

4

使用Lambda的Python Quicksort

我在博客上写的内容:

qsort = lambda seq: [] if not seq else qsort(filter(lambda n: n<=seq[0], seq[1:]))+[seq[0]]+qsort(filter(lambda n: n>seq[0], seq[1:]))

这是实际的博客文章


1
不错的解决方案!Python中已知最短的快速排序只有79个字节长(由传奇传奇代码作家Mark Byers提供):news.e-scribe.com/314#581
hallvabo 2012年

这是一个非常深奥的解决方案。吓到我了!
MrD 2012年

4

红宝石

#get user input from standard input and store it in a variable
var = gets
#make user input into a ruby array in a string
array_string = '[' + var + ']'
#evaluate this ruby array and store the array in a variable
array = eval(array_string)
#convert from strings to integers
#initialize loop variable as 0
i = 0
#loop until the loop variable is no longer small enough
#to be a valid index of the array
until !(i < array.length)
    #convert to a number then ensure it is an integer
    array[i] = array[i].to_f.floor
    #increment i
    i = i + 1
end

sorted = false

#infinite loop
while true
    #if it hasn't been sorted
    if ((!sorted) == true)
        #try to sort it
        #initialize loop variable as 0
        j = 0
        #loop while i is less than or equal to the length of the array
        while (i <= array.length)
            random = rand # get a random number
            #this gets a zero or one
            random = (random + random.round).floor
            #turn random into a boolean
            if random == 0
                random = true
            end
            if random == 1
                random = false
            end
            #don't do anything if this is the last one
            if j == (array.length - 1)
                #do nothing
            else
                if random == true
                    #true means keep these 2 elements in the same order
                end
                if random == false
                    #false means swap with next element
                    #initialize a variable to store the current element
                    swapvar = array[j]
                    #initialize a variable to store the next element
                    swapvar2 = array[j+1]
                    #set the current element to what was the next element
                    array[j] = swapvar2
                    #set the next element to what was in this one
                    array[j+1] = swapvar
                end
            end
            #increment j
            j = j + 1
            #loop kept looping, fixed now
            if j >= array.length
                break
            end
        end
        #now test if it is sorted
        #lets say it is
        sorted = true
        #now see if we are wrong
        #initialise a loop variable to zero
        k = 0
        while (array.length > k)
            #get current value from array and store it in a variable
            current = array[k]
            #get current value from array and store it in a variable
            next_ = array[k + 1]
            if !(array[k +1].nil? == true)#stop errors
                #if sorted correctly
                if next_ < current || next_ == current
                    #sorted stil== true
                else
                    sorted = false #not sorted, try again
                end
            end
            #increment loop variable
            k = k + 1
        end
            #DEBUG
        #p array
    else
        break #break out of infinite loop
    end
end


#it is now sorted in descending order
#we want ascending so lets flip it

#initialise a loop variable to zero
l = 0

final_array = Array.new([])

while (l <= (array.length - 1))
    final_array[array.length - l - 1] = array[l]
    #increment loop variable
    l += 1
end

#now we need to make it into a string
str = ''

#first map each element to a string
#to do this lets extend Array, then use this for our array
class Array
    def map #map each element to a string
        #initialise a loop variable to zero
        @m = 0
        arr = []
        while @m < self.length
            arr += [self[@m].to_s]
            #increment loop variable
            @m = @m + 1
        end
        return arr
    end
end

final_array = Array.new(final_array).map()
#DEBUG
#p final_array

#now add the elements to a string, separated by commas and spaces
#initialise a loop variable to zero
n = 0

while n < array.length
    #increment loop variable
    #add item to string
    str = str + final_array[n]
    #if not last item
    if !((array.length - 1 )== n)
        #add comma
        str += ','
    end
    #if not last item
    if !((array.length - 1 )== n)
        #add space
        str += ' '
    end
    n = n + 1
end

#now print the string
puts str

3

C ++(4409)

#include <iostream>
#include <cstdlib>
#include <cctype>
#include <string>
#include <sstream>


std::string itostr(int number)
{
   std::stringstream ss;
   ss << number;
   return(ss.str());
}


class CStackLIFO
{
private:
    int* stack;
    size_t len;
public:
    CStackLIFO();
    CStackLIFO(int);
    ~CStackLIFO();
    void init();
    void init(int);
    void push(int);
    int pop();
    int pop(int&);
    void destroy(size_t);
    int get(size_t);
    size_t get_len();
};


void CStackLIFO::init()
{
    len = 0;
    stack = NULL;
}


void CStackLIFO::init(int val)
{
    len = 1;
    stack = new int[len];
    stack[0] = val;
}


CStackLIFO::CStackLIFO()
{
    init();
}


CStackLIFO::CStackLIFO(int val)
{
    init(val);
}


CStackLIFO::~CStackLIFO()
{
    len = 0;
    delete[] stack;
    stack = NULL;
}


void CStackLIFO::push(int val = NULL)
{
    if((stack == NULL) || (len == 0))
    {
        this->init(val);
    }
    else
    {
        int* buf = stack;
        len++;
        stack = new int [len];

        for(size_t i = 0; i < (len - 1); i++)
        {
            stack[i] = buf[i];
        }

        stack[len - 1] = val;
        delete[] buf;
    }
}


int CStackLIFO::pop()
{
    int val;
    int* buf = stack;
    len--;
    stack = new int [len];

    for(size_t i = 0; i < len; i++)
    {
        stack[i] = buf[i];
    }

    val = buf[len];
    delete[] buf;

    return(val);
}


int CStackLIFO::pop(int &out)
{
    if(len <= 0)
        return(false);

    int* buf = stack;
    len--;
    stack = new int [len];

    for(size_t i = 0; i < len; i++)
    {
        stack[i] = buf[i];
    }

    out = buf[len];
    delete[] buf;

    return(true);
}


void CStackLIFO::destroy(size_t idx)
{
    int* buf = stack;
    len--;
    stack = new int [len];
    for(size_t i = 0; i < idx; i++)
    {
        stack[i] = buf[i];
    }
    for(size_t i = idx; i < len; i++)
    {
        stack[i] = buf[i + 1];
    }
    delete[] buf;
}


int CStackLIFO::get(size_t idx)
{
    return(stack[idx]);
}


size_t CStackLIFO::get_len()
{
    return(len);
}


class CSort
{
private:
    void removeWhitespace();
public:
    std::string in;
    void sort();
    void display();
};


void CSort::display()
{
    std::cout << in << std::endl;
    return;
}


void CSort::removeWhitespace()
{
    for(size_t i = 0; i < in.size(); i++)
    {
        if(in[i] == ' ')
        {
            in = in.substr(0, i) + in.substr(i+1);
        }
    }
}


void CSort::sort()
{
    removeWhitespace();

    CStackLIFO nums;
    CStackLIFO s;

    // build stack
    for(size_t i = 0, offset = 0; i < in.size(); i++)
    {
        for(offset = 0; (i + offset) < in.size(); offset++)
        {
            if(!(isdigit(in[i + offset]) ||
                 (in[i + offset] == '-')))
                break;
        }

        if(offset > 0)
        {
            nums.push(atoi(in.substr(i, offset).c_str()));
        }

        i += offset;
    }

    // sort
    for(size_t lowest = 0; 0 < nums.get_len(); lowest = 0)
    {
        for(size_t i = 0; i < nums.get_len(); i++)
        {
            if(nums.get(i) < nums.get(lowest))
                lowest = i;
        }

        s.push(nums.get(lowest));
        nums.destroy(lowest);
    }    

    // convert to string
    in = "";
    for(size_t i = 0; i < s.get_len(); i++)
    {
        // Convert num to string
        in += itostr(s.get(i));
        in += ", ";
    }
    if(in.size() > 2)
        in = in.substr(0, in.size() - 2);
}


int main(int argc, char* argv[])
{
    while(1)
    {
        CSort unsorted;
        unsorted.in = "";

        while(1)
        {
            std::string userin = "";
            std::cin >> userin;

            if(userin.compare("end") == 0)
                break;

            unsorted.in += userin + ", ";
        }

        unsorted.in = unsorted.in.substr(0, unsorted.in.size() - 2);

        CSort sorted;
        sorted.in = unsorted.in;
        sorted.sort();

        std::cout << "Input:" << std::endl;
        unsorted.display();
        std::cout << "Output:" << std::endl;
        sorted.display();
    }

    return(0);
}

该程序有些“坏”之处:

  • 真的很严格。:)我可以直接输入数字,而不用解析字符串的数字。

  • 使用过多的类。我也可以使用内置的,但是糟糕的编码器只会重新发明轮子。

  • 排序的循环效率极低。我认为这是最慢的方法,而没有让它看起来像我实际上在尝试使其变慢。实际上,代码的实际“排序”部分仅包含11行,包括花括号和换行符。


3

这个是O(n * n!)

from itertools import permutations, izip, islice
L=[10,9,8,7,6,5,4,3,2,1]
for l in permutations(L):
    if all([i<j for i,j in izip(L, islice(L,1,None))]):
        break
print l

它迭代列表的所有排列并测试它们是否已排序。它是如此可怕的是排序仅有10项需要17秒

$ time python badsort.py 
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

real    0m17.563s
user    0m17.537s
sys     0m0.020s

3

T-SQL

(SQL Server 2008 R2)

自然,在T-SQL中,您可以使用“ ORDER BY”进行排序。h

DECLARE @LISTIN NVARCHAR(MAX);
SELECT @LISTIN = N'1, 4, 7, 2, 5'; --Input list goes here.
DECLARE @LISTINDEX BIGINT;
SELECT @LISTINDEX = 0;
DECLARE @CHARS NVARCHAR(MAX);
SELECT @CHARS = N'';
DECLARE @LISTOUT NVARCHAR(MAX);
SELECT @LISTOUT = N'';
DECLARE @ORDERBY TABLE (NUMBER NVARCHAR(MAX));
WHILE @LISTINDEX < LEN(@LISTIN) BEGIN;
SELECT @LISTINDEX = @LISTINDEX + 1;
SELECT @CHARS = @CHARS + SUBSTRING(@LISTIN, @LISTINDEX, 1);
IF PATINDEX(N'%, ', @CHARS) > 0 BEGIN;
INSERT INTO @ORDERBY (NUMBER) VALUES (REPLACE(@CHARS, N', ', N''));
SELECT @CHARS = N'';
END;
IF @LISTINDEX = LEN(@LISTIN) BEGIN;
INSERT INTO @ORDERBY (NUMBER) VALUES (@CHARS);
END;
END;
DECLARE ORDERBY CURSOR FOR SELECT NUMBER FROM @ORDERBY ORDER BY CONVERT(DECIMAL, NUMBER);
OPEN ORDERBY;
FETCH NEXT FROM ORDERBY INTO @CHARS;
WHILE @@FETCH_STATUS = 0 BEGIN;
SELECT @LISTOUT = @LISTOUT + @CHARS + N', ';
FETCH NEXT FROM ORDERBY INTO @CHARS;
END;
CLOSE ORDERBY;
DEALLOCATE ORDERBY;
IF @LISTOUT = N'' SELECT @LISTOUT;
ELSE SELECT SUBSTRING(@LISTOUT, 1, LEN(@LISTOUT) - 1);

看到“ ORDER BY”了吗?它就在游标声明中。


2

Funnel Sort的Python实现。如果正确实施,该算法实际上可以具有良好的缓存性能,在这种情况下,它肯定不是(但是可以正确排序)。

class Funnel(object):
  """ In place funnel sorting algorithm. """
  def __init__(self, left_child, right_child):
    self.left_child = left_child
    self.right_child = right_child
    self.lookahead = (False, -1)

  def get_next(self):
    if self.left_child.has_next() and self.right_child.has_next():
      l, r = self.left_child.get_next(), self.right_child.get_next()
      if l < r:
        self.right_child.put_back(r)
        return l
      else:
        self.left_child.put_back(l)
        return r
    elif self.left_child.has_next():
      return self.left_child.get_next()
    elif self.right_child.has_next():
      return self.right_child.get_next()
    else:
      raise Exception("Out of elements.")

  def has_next():
    if self.lookahead[0]: 
      self.lookahead = (False, self.lookahead[1])
      return self.lookahead[1]
    return self.left_child.has_next() or self.right_child.has_next()

  def put_back(self, item):
    self.lookahead = (True, item)

class Funnel_Base(Funnel):
  def __init__(self, buffer):
    self.buf = buffer
    self.lookahead = (False, -1)

  def get_next(self):
    if self.lookahead[0]:
      self.lookahead = (False, self.lookahead[1])
      return self.lookahead[1]
    return self.buf.pop(0)

  def has_next():
    return len(self.buf) > 0

def make_funnel(funnels):
  while len(funnels) > 1: funnels.append(Funnel(funnels.pop(0), funnels.pop(0)))
  return funnels[0]

def insertion_sort(array):
  def swap(i, j):
    t = array[i]
    array[i] = array[j]
    array[j] = t
  for i in xrange(1,len(array)):
    while i > 0 and  array[i] < array[i-1]:
      swap(i, i-1)
      i -= 1

def funnel_sort_internal(array):
  if len(array) < 100:
    # sort subsections with insertion sort and make base funnels
    insertion_sort(array)
    return Funnel_Base(array)
  else:
    K = int(len(array)**(1.0/3))
    new_funnels = [funnel_sort_internal(array[base:min(base+K, len(array))])
                   for base in xrange(0, len(array), K)]
    return make_funnel(funnels)

def funnel_sort(array):
  cp = array[:]
  srtd = funnel_sort_internal(cp)
  for i in xrange(len(array)): array[i] = cp[i]

2

对32位整数列表进行排序。对于大多数普通情况,它实际上是非常有效的:

#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

static unsigned char *bmp[131072];
static size_t total, printed;

static void set(int n);
static void print_page(unsigned char *page, int offset);
static void print_number(int n);

int main(void)
{
    int i, n;

    assert(INT_MIN == -2147483647 - 1 && INT_MAX == 2147483647);

    while (scanf("%d,*", &n) > 0) {
        set(n);
        total++;
    }

    for (i = 0; i < 131072; i++)
        if (bmp[i] != NULL)
            print_page(bmp[i], INT_MIN + i * 32768);
    putchar('\n');

    return 0;
}

static void set(int n)
{
    unsigned int i = n - INT_MIN;

    if (bmp[i >> 15] == NULL)
        bmp[i >> 15] = calloc(4096, sizeof(unsigned char));

    bmp[i >> 15][(i >> 3) & 4095] |= (unsigned int)1 << (i & 7);
}

static void print_page(unsigned char *page, int offset)
{
    int i, j;

    for (i = 0; i < 4096; i++, offset += 8)
        if (page[i])
            for (j = 0; j < 8; j++)
                if (page[i] & (1 << j))
                    print_number(offset + j);
}

static void print_number(int n)
{
    printf("%d%s", n, ++printed < total ? ", " : "");
}

例:

$ echo '1, 4, -3, 7, -2147483648, 2147483647, 2, 5' | ./bitmap-sort
-2147483648, -3, 1, 2, 4, 5, 7, 2147483647

2
<?php
    /*  THIS SOFTWARE IS PROVIDED "AS IS" AND ANY
        EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
        BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
        OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
        PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
        REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
        INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
        CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
        TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
        INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
        LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
        IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
        ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.          */

    // Make the function
    function sort_numbers($nums) {
        // Remove duplicates from array
        array_unique($nums);
        // Filter out everything that's not a number or a numeric string
        foreach ($nums as $val) {
            if (!is_numeric($val)) {
                unset($array[$val]);
            }
        }
        // Do some random computations
        class SorterFunction {
            public $timestamp = 0;
            public $rand_num = 0;
            public function sort_a_numeric_array($num_arr) {
                // Sort the array
                sort($num_arr, SORT_NUMERIC);
                return $num_arr;
            }
            public function __construct() {
            $this->timestamp = time();
            $this->rand_num = rand() % 100000;
        }
    }
    // Create a new SorterFunction class
    $MySorterFunction = new SorterFunction();
    // Print out the sorted array's elements using var_dump
        $MySorterFunction->sort_a_numeric_array($nums);
        var_dump($nums);
    }
    $my_nums = array(1, 4, 7, 2, 5);
    sort_numbers($my_nums);
?>

那甚至都行不通,因为sort()按引用工作,甚至都不返回任何东西……
ircmaxell

@ircmaxell:固定,谢谢。
nyuszika7h 2011年

叹。(尽管它是wtf,所以从技术上来说很重要)。但是它仍然不起作用(错误的分类更改)
ircmaxell

1
+1许可,但可能涵盖更多行。

1
@Tim查看更新。;)
nyuszika7h

2

C ++,不确定是否有这种名称,但是这里<ducks for cover/>

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

int main(void)
{
  std::istream_iterator<int> in(std::cin), end;
  std::vector<int> input(in, end);

  std::cout << "sorting.." << std::endl;
  std::copy(input.begin(), input.end(), std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;

  // this is the smart bit.. ;)
  while (std::next_permutation (input.begin(), input.end()));

  std::cout << "sorted.." << std::endl;
  std::copy(input.begin(), input.end(), std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;

  return 0;
}

它与BogoSort相似,不同之处在于,您的最差情况复杂度是Bogosort的平均情况复杂度。
saeedn 2011年

2

企业解决方案(使用伪代码):

create sql connection
create temporary table: one autoincrementing ID field and one value field
convert array into xml
post xml to sql database
use stored procedure to create records from xml
run sql command "select * from temptable sort by value"
iterate records, adding to array
drop temporary table
close connection

2

在Ruby中,“ 意大利面条排序”的可视化表示形式,旨在在80列终端中运行:

$CONSOLE_WIDTH = 78
def sort a
  factor = $CONSOLE_WIDTH.to_f/a.max
  puts "Strands:"
  puts (strands=a.map{|v|['-'*(v*factor).to_i,v*factor]}).map{|s|s.first}
  results=[];
  len=0
  n = 1
  until strands.empty? do
   #puts "\nITERATION #{n}\n\n"
    n+=1
    $CONSOLE_WIDTH.downto(0) do |i|
      len = i
      contacts = strands.find_all{|s|s.first[i]!=nil}
      break unless contacts.empty?
    end
    puts "\nResults:"
    puts results.map{|s|s.first}
    puts "\nStrands:"
    puts strands.map{|s|s.first.ljust(len+1)+"|"}
    longest = strands.sort_by{|s|s.last}.max
    strands.delete_at strands.index(longest)
    results << longest
  end
  puts "\nResults:"
  puts results.map{|s|s.first}
  return results.map{|s|s.last/factor}

end

用法: p sort (1..10).map{rand(100)}


2

PL \ SQL-109行

这是对@eBusinesss在@steenslag的答案中的评论的回应。它没有任何用处。

它分为四个阶段:

  1. 用逗号分隔的数字列表,计算出其中有多少个逗号。
  2. 使用逗号数可以根据逗号在位置上分割字符串。
  3. 遍历已知数量的值并每次都找到最小值-我们删除先前的最小值。
  4. 输出它们。

 create or replace procedure sort ( Plist_of_numbers varchar2 ) is

   type t_num_array is table of number index by binary_integer;

   t_sorted t_num_array;
   t_unsorted t_num_array;

   i binary_integer := 0;
   -- Can you tell this one was an afterthought?
   x binary_integer := 0;

   no_of_commas integer := 0;

   v_list_of_numbers varchar2(32000);
   v_min_value number;
   v_min_index binary_integer;

begin

   -- Best to be overly careful about these things.
   if trim(Plist_of_numbers) is null then
      raise_application_error(-20000,'You need to give me something to work with.');
   end if;

   -- Firstly we have to make sure that there is a trailing comma
   -- in Plist_of_numbers for this to work.
   if substr(Plist_of_numbers,-1) = ',' then
      v_list_of_numbers := Plist_of_numbers;
   else
      v_list_of_numbers := Plist_of_numbers || ',';
   end if;


   /* SQL ( being SQL ) we had to pass in a string of numbers
      because we'd need to create a type outside the function which
      wouldn-t really be in the spirit of things so, let's unpack
      our string. In order to do this ( bowling ) we need to know how
      many commas are in our sting.
   */

   for j in 1 .. length(v_list_of_numbers) loop

      if substr(v_list_of_numbers,j,1) = ',' then
         no_of_commas := no_of_commas + 1;
      end if;

   end loop;


   -- Next we unpack our list into t_unsorted;
   for j in 1 .. ( no_of_commas - 1 ) loop

      i := i + 1;
      t_unsorted(i) := to_number( substr( v_list_of_numbers
                                        , instr(v_list_of_numbers, ',', 1, j)
                                        , instr(v_list_of_numbers, ',', 1, j + 1)
                                           )
                                  );

   end loop;


   -- Next the actual sorting.
   -- Loop through the known number of elements in the array.
   for j in 1 .. i loop

      -- Then the array each time to find the minimum.
      -- As we-re deleting stuff in the middle here we have to be careful;
      k := t_unsorted.first;
      v_min_value := null;

      while k < t_unsorted.last loop

         if v_min_value is null then 
            v_min_value := t_unsorted(k);
            v_min_index := k;
         elsif t_unsorted(k) < v_min_value then
            v_min_value := t_unsorted(k);
            v_min_index := k;
         end if;

         k := t_unsorted.next;

      end loop;

      -- Now we-ve found the next minimum value put it into the 
      -- t_sorted array
      x := x + 1;          
      t_sorted(x) := v_min_value;
      -- and delete our min value from the unsorted array.
      t_unsorted.delete(v_min_index);

   end loop;


   -- Lastly show that everything worked.
   for j in 1 .. x loop

      dbms_output.put_line( t_sorted(j) );

      -- it-s also nice to show the wider world what-s happening 
      -- but let-s not do it too often, server load etc.
      if mod(j,10) = 0 then
          dbms_application_info.set_module('finding min', 'total: ' || j );
      end if;

   end loop;

end sort;

如您所见,这很荒谬……坏事包括:

  • 在SQL中执行此操作

实际上就差不多了,应该很快。


2

语言和算法的选择都需要说明。

该算法称为慢速排序。我打算击败bogosort(测试随机排列,直到对其进行排序),因为尽管在算法上效率非常低下,但是它的实现太简单了,您不能保证它的缓慢性。

我用Scheme编写慢速排序,因为Scheme的主要目标是简单,这使挑战变得更大。Scheme的一个有趣功能是其无与伦比的可扩展性。实际上,该语言的实现通常(通常是完全)在Scheme本身中实现。甚至更好:您需要的只是抽象(lambda)和应用程序。应用程序以前缀表示法评估:

(function arg1 arg2 ...)

...只是以下方面的语法糖:

(apply function (list arg1 arg2 ...))

...将函数应用于参数列表。

为了消除此代码保龄球,我必须重新定义max函数以递归方式拆分列表,直到它可以进行比较为止。通过移除所有最大值直到剩下一个数,还可以使用max递归地重新定义min函数。最后,通过连续添加最小值来重新定义排序。

慢速排序基于“乘除”,而不是“分而治之”。它的工作方式是递归地拉出最大值,直到剩下最小值为止,每次将所得的最小值附加到解决方案中,然后重新启动,直到依次将所有最小值都附加完为止。虽然完全无效,但是我的实现会尽可能地重用计算,因为:1)算法需要它2)您可能希望这种排序结束一天……

(define sort
  (lambda ns
    (define max
      (lambda (ns)
        (let ([len (length ns)])
          (case len
            [(2) (receive (a b) (car+cdr ns)
                   (if (> a b) a b))]
            [(1) (car ns)]
            [else (receive (a b)
                    (split-at ns
                      (floor (/ len 2)))
                    (let ([ma (max a)]
                          [mb (max b)])
                      (if (> ma mb) ma mb)))]))))
    (define min
      (lambda (ns)
        (if (null? (cdr ns)) (car ns)
            (min (remove ns (max ns))))))
    (if (every number? ns)
        (let sort ([ns ns] [sorted (list)])
          (if (null? ns) sorted
              (let ([m (min ns)])
                (sort (remove ns m)
                  (append ns m)))))
    (error "These are not all numbers: " ns))))

1

Java夸张的混乱/沉重

那很有趣!觉得很奇怪发布这样的事情。

import java.util.LinkedList;

public class WTF {

    // XXX We all know linkedlists are awesome for random access!
    public static LinkedList<Integer> sort(LinkedList<Integer> array) {
        // XXX Instead of sorting in place, we create another array entirely!
        LinkedList<Integer> result = new LinkedList<Integer>();

        // while array is not all null
        // XXX No comments!
        boolean arrayAllNull = true;
        for (int a = 0; a < array.size(); a = a + 1) {
            if (array.get(a) != null) {
                arrayAllNull = false;
            }
        }

        while (arrayAllNull != true) {

            // XXX We could use Integer.MAX_VALUE, but lets assumes something instead
            Integer i = 999999999;
            // find lowest
            for (int a = 0; a < array.size(); a = a + 1) {
                if (array.get(a) != null) {
                    if (array.get(a) < i) {
                        i = array.get(a);
                    }
                }
            }

            // replace lowest by null
            // XXX Yup, another loop! :)
            // XXX We're breaking the original array, but don't tell anyone.
            for (int a = 0; a < array.size(); a = a + 1) {
                if (array.get(a) != null) {
                    if (array.get(a) == i) {
                        array.set(a, null);
                    }
                }
            }

            result.add(i);

            // XXX Lets repeat that test once again, functions are bad.
            arrayAllNull = true;
            for (int a = 0; a < array.size(); a = a + 1) {
                if (array.get(a) != null) {
                    arrayAllNull = false;
                }
            }

        }

        return result;
    }

    public static void main(String[] args) {
        int[] numbers = new int[]{1, 4, 7, 2, 5};
        LinkedList<Integer> nums = new LinkedList<Integer>();
        for (int i : numbers)
            nums.add(i);
        System.out.println(sort(nums));
    }

}

1

蟒蛇

仅当所有项目均小于9e99时才有效:)

>>> L=[10,9,8,7,6,5,4,3,2,1]
>>> 
>>> print [[min(L),L.__setitem__(L.index(min(L)),9e99)][0] for i in L]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

每次循环时,提取最小的元素并将其替换为9e99


1

蟒蛇皮(634)

如果列表已排序,请打印它。否则,交换两个顺序错误的元素,然后生成处理新顺序的python脚本。运行该脚本后,删除创建的脚本。

list_to_sort = input()
n = 0
n += 1
import sys, os
for i in range(len(list_to_sort)-1):
    if list_to_sort[i]>list_to_sort[i+1]:
        (list_to_sort[i],list_to_sort[i+1]) = (list_to_sort[i+1],list_to_sort[i])
        source_file = open(sys.argv[0],'r')
        temp_filename = 'temp'+repr(n)+'.py'
        temp_file = open(temp_filename,'w')
        temp_file.write('list_to_sort = ' + repr(list_to_sort) + '\n')
        temp_file.write('n = ' + repr(n) + '\n')
        for line in source_file.readlines()[2:]:
            temp_file.write(line)
        source_file.close()
        temp_file.close()
        os.system('python ' + temp_filename)
        os.remove(temp_filename)
        sys.exit(0)
print list_to_sort

1

Python中的Bogobogosort

import random
import copy

def isSorted(list):
    newlist = copy.deepcopy(list)
    while True:
        newlist[:len(newlist)-1] = bogobogosort(newlist[:len(newlist)-1])
        if newlist[len(newlist)-2] < newlist[len(newlist)-1]:
            break
        random.shuffle(newlist)
    return newlist == list

def bogobogosort(list):
    ret = copy.deepcopy(list)
    if (len(ret) > 1):
        while not isSorted(ret):
            random.shuffle(ret)
    return ret

David Morgan-Mar发明的算法。

警告:请勿对任何大于5个元素的列表进行尝试。即使是5也很慢。


1

蟒蛇

我的解决方案。包括错误处理,以及在对数字进行排序时保留空白的功能,即空白留在原处;数字移动。

例如,

Please tell me your favorite list of numbers.
I'll sort them for you.  
7, 8, 6, 7, 1, 3, 5
1, 3, 5, 6, 7, 7, 8

9,  6  ,8, 43, 90, 13   , 54, 3223, 4
4,  6  ,8, 9, 13, 43   , 54, 90, 3223

码:

#!/usr/bin/env python
import sys
import re

class SillyUserException(ValueError):
    def __init__(self, reason, input):
        self.reason = reason
        self.input = input

    def __str__(self):
        return '''
"No man is exempt from saying silly things; the mischief is to say them deliberately."
 - Michel de Montaigne, The Complete Essays
 Your offense was {}.  You should know that it's {}.
         '''.format(self.input, self.reason)

class Item(object):
    def __init__(self, number, prespace, postspace):
        self.number = number
        self.prespace = prespace
        self.postspace = postspace

    def __str__(self):
        return self.prespace + str(self.number) + self.postspace

class ListOfNumbers(object):
    def __init__(self, string):
        self.array = self.parse(string)

    def __str__(self):
        outs = ''
        for i in self.array:
            outs += '{}{}{},'.format(i.prespace, i.number, i.postspace)
        return outs[:-1]

    def parse(self, string):
        array = []

        for item in string.split(','):
            try:
                x = int(item)
            except ValueError:
                raise SillyUserException("not a number", item)

            whitespace = re.findall("\s+", item)
            pre = ''
            post = ''
            if len(whitespace) > 0:
                pre = whitespace[0]
            if len(whitespace) > 1:
                post = whitespace[-1]

            array.append(Item(x, pre, post))

        def swap(i, j):
            tmp = array[i].number
            array[i].number = array[j].number
            array[j].number = tmp

        def min(arr, offset):
            m = arr[0]
            index = 0
            for i, e in enumerate(arr):
                if e.number < m.number:
                    m = e
                    index = i
            return index + offset


        for i, x in enumerate(array):
            m = min(array[i:], i)
            if m != i:
                swap(m, i)

        return array


if __name__ == "__main__":
    sys.stdout.writelines('\n'.join([
        "Please tell me your favorite list of numbers.",
        "I'll sort them for you.  ",
        ""
    ]))

    sys.stdout.flush()

    def read_lines():
        while True:
            line = raw_input()
            yield line

    try:
        for line in read_lines():
            if not line:
                raise SillyUserException('polite to speak when asked a question.', "<nothing>")
            if line.strip() == '42':
                raise SillyUserException('the answer to life, the universe, and everything',
                    'using and overly powerful value')
            if ',' not in line:
                raise SillyUserException("not a list", line)


            print ListOfNumbers(line)

    except SillyUserException as sillyness:
        print sillyness

1

Python 3

该程序在标准输入上接受空格分隔的数字列表。然后,它将以正确的顺序打印标准输出。最终。

import base64, pickle
pickle.loads(base64.b64decode(b'gAIoY2J1aWx0aW5zCmxpc3QKcQBjYnVpbHRpbnMKbWFwCnEBY2J1aWx0aW5zCmludApjYnVpbHRpbnMKZ2V0YXR0cgpxAmNidWlsdGlucwppbnB1dAopUlgFAAAAc3BsaXSGUilShlKFUnEDaABoAWNmdW5jdG9vbHMKcGFydGlhbApxBGNvcGVyYXRvcgphZGQKY19vcGVyYXRvcgpuZWcKY2J1aWx0aW5zCm1pbgpoA4VShVKGUmgDhlKFUnEFaABoAWgCY2FzeW5jaW8KZ2V0X2V2ZW50X2xvb3AKcQYpUlgKAAAAY2FsbF9sYXRlcoZSaAVoAWgEaARjYnVpbHRpbnMKcHJpbnQKhlJoA4ZSh1KFUjFoAmgGKVJYEgAAAHJ1bl91bnRpbF9jb21wbGV0ZYZSY2FzeW5jaW8Kc2xlZXAKY19vcGVyYXRvcgphZGQKY2J1aWx0aW5zCm1heApoBYVSSwGGUoVShVIu'))

说明:pickle协议实际上提供了很多自由,最引人注目的是使用参数导入和调用任意对象的自由。最突出的限制是,泡菜VM没有任何类型的流控制,因此,在泡菜VM中纯粹实现的任何代码都必须使用python标准库函数内部的流控制才能获得类似的效果。排序的这种实现方式使用了基于协程的睡眠排序,该睡眠排序由迭代器的自由应用程序和部分应用程序构建而成。

等效的python代码如下所示:

from asyncio import get_event_loop, sleep
from operator import add
from functools import partial
values = list(map(int, input().split()))
times = list(map(partial(add, -min(values)), values))
list(map(get_event_loop().call_later, times, map(partial(partial, print), values)))
get_event_loop().run_until_complete(sleep(max(times)+1))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.