IOS学习 NSMutableArray中元素排序

首先(效率同于冒泡):

   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总数量会变多。

UIViewsubviewarrayaddsubview一个已存在只是将subview放到最上层,并不会有两个相同对象subview出现。

replaceObjectAtIndex:0 withObject:Object Object代替第0个对象,如果Object已经是Array中的一员,Array中就会有两个Object

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章