Objective-C で Sleep sort

元ネタ:4chan BBS – Genius sorting algorithm: Sleep sort
紹介されていたのは:常識を覆すソートアルゴリズム!その名も”sleep sort”!

面白そうだなぁと思ったので、Objective-c で書いてみた。

@implementation SleepSorter
- (void) doit:(id)n
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [NSThread sleepForTimeInterval:[n intValue]];
    NSLog(@"%d", [n intValue]);
    [pool release];
}
@end
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    id sorter = [SleepSorter alloc];
    NSArray *list = [NSArray arrayWithObjects:
        [NSNumber numberWithInt:3],
        [NSNumber numberWithInt:1],
        [NSNumber numberWithInt:8],
        [NSNumber numberWithInt:7],
        [NSNumber numberWithInt:2],
        [NSNumber numberWithInt:4],
        [NSNumber numberWithInt:9],
        [NSNumber numberWithInt:6],
        [NSNumber numberWithInt:0],
        [NSNumber numberWithInt:5], nil];
    for (id target in list) {
        // [sorter doit:[target intValue]]; // 普通に呼び出す場合
        [NSThread detachNewThreadSelector:@selector(doit:)
            toTarget:sorter withObject:target];
    }
    [NSThread sleepForTimeInterval:30]; // 結果が表示する前に終わっちゃう、、、
    [pool drain];
    return 0;
}

ちなみに結果は、、、

実行中...
2011-05-20 12:41:10.364 Untitled[2908:4403] 0
2011-05-20 12:41:11.364 Untitled[2908:2903] 1
2011-05-20 12:41:12.364 Untitled[2908:3503] 2
2011-05-20 12:41:13.364 Untitled[2908:1303] 3
2011-05-20 12:41:14.364 Untitled[2908:3903] 4
2011-05-20 12:41:15.365 Untitled[2908:4903] 5
2011-05-20 12:41:16.364 Untitled[2908:4003] 6
2011-05-20 12:41:17.364 Untitled[2908:3103] 7
2011-05-20 12:41:18.364 Untitled[2908:2d03] 8
2011-05-20 12:41:19.366 Untitled[2908:3d03] 9
Debugger stopped.
Program exited with status value:0.

おー並んでる!

配列の初期化がかっこ悪いですね、、、
各所、こうしたらスマートじゃん?みたいな指摘がありましたら、よろしくお願いします。

Leave a comment

1 Comments.

コメントをどうぞ

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*


次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <img localsrc="" alt="">

Trackbacks and Pingbacks: