MergeSortのiPhoneサンプルコード描いてみます。。。。
動かすとこんな。。。。
サンプルコード
#import “ViewController.h”
@interface ViewController ()
@property (nonatomic, strong) NSMutableArray *arr;
@property int counter;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.arr = [[@”6 5 2 7 3 1 2 6″ componentsSeparatedByString:@” “] mutableCopy];
for (int i=0; i<self.arr.count; i++) {
[self showText:self.arr[i] atIndex:i];
}
self.counter ++;
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self mergeSort:self.arr indexP:0 indexR:self.arr.count–1];
}
– (void)mergeSort:(NSMutableArray *)a indexP:(int)p indexR:(int)r
{
if (p < r) {
int q = (p + r) / 2;
[self mergeSort:a indexP:p indexR:q];
[self mergeSort:a indexP:q+1 indexR:r];
[self mergeSort:a indexP:p indexQ:q indexR:r];
}
}
– (void)mergeSort:(NSMutableArray *)a indexP:(int)p indexQ:(int)q indexR:(int)r
{
int n1 = q – p + 1;
int n2 = r – q;
int L[n1 + 1];
int R[n2 + 1];
for (int i=0; i<n1; i++)
L[i] = [a[p + i] intValue];
for (int j=0; j<n2; j++)
R[j] = [a[q + j + 1] intValue];
L[n1] = HUGE_VAL;
R[n2] = HUGE_VAL;
int i=0;
int j=0;
for (int k=p; k<=r; k++) {
if (L[i] <= R[j]) {
a[k] = @(L[i]);
i++;
} else {
a[k] = @(R[j]);
j++;
}
[self showText:[a[k] stringValue] atIndex:k];
}
self.counter++;
}
– (void)showText:(NSString*)s atIndex:(int)k
{
float y = 0;
float delay = 0;
if (self.counter == 1
|| self.counter == 2
|| self.counter == 4
|| self.counter == 5)
{
y = 300;
delay = 1.5 + self.counter * 1.0;
} else if (self.counter == 3 || self.counter == 6) {
y = 200;
delay = 6.0 + self.counter * 0.5;
} else if (self.counter == 7){
y = 100;
delay = 10.0;
} else {
y = 400;
}
UILabel *l = [[UILabel alloc] init];
l.text = s;
l.font = [UIFont boldSystemFontOfSize:20];
l.center = CGPointMake(k * 30 + 50, y);
[l sizeToFit];
[self.view addSubview:l];
l.transform = CGAffineTransformMakeTranslation(0, 500);
[UIView animateWithDuration:1.0 delay:delay options:0 animations:^{
l.transform = CGAffineTransformIdentity;
} completion:^(BOOL finished) {}];
}
@end