首先(效率同于冒泡):
int comparecCount = 0;
NSMutableArray *array = [[NSMutableArrayalloc]initWithObjects:@"5",@"9",@"2",@"4",@"8",@"1",@"7",@"3",nil];
for (inti = [array count] -1; i > 0; i--)
{
for (int j =0; j< i; j++)
{
comparecCount++;
if([[array objectAtIndex:i] integerValue] < [[arrayobjectAtIndex:j]integerValue])
{
[array exchangeObjectAtIndex:iwithObjectAtIndex:j];
}
}
}
输出比较的次数为:28
有序,只想把新来的元素插在哪里即可:
for (inti =0; i < [array count]; i++)
{
for (int j =0; j< i; j++)
{
comparecCount++;
if ([[array objectAtIndex:i] integerValue]< [[array objectAtIndex:j]integerValue])
{
idtemp = [arrayobjectAtIndex:i];
[array removeObject:temp];
[array insertObject:tempatIndex:j];
break;
}
}
}
输出比较的次数为:17
备注:要多说一些细节,大家往NSMutableArray中插入一个元素(即使已经存在于数组中)insertObject总数量会变多。
UIView的subview的array中addsubview一个已存在只是将subview放到最上层,并不会有两个相同对象subview出现。
replaceObjectAtIndex:0 withObject:Object Object代替第0个对象,如果Object已经是Array中的一员,Array中就会有两个Object。