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

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