ios - How to Sorting Mutable Array of NSNumbers using for Loop in Objective C? -
i tried this, not successful. can 1 sort problem?
nsnumber *num1= [nsnumber numberwithint:5]; nsnumber *num2= [nsnumber numberwithint:3]; nsnumber *num3= [nsnumber numberwithint:7]; nsnumber *num4= [nsnumber numberwithint:9]; nsnumber *num5= [nsnumber numberwithint:2]; nsmutablearray *array =[nsmutablearray arraywithobjects:num1,num2,num3,num4,num5, nil]; int numlength = [array count]; int tempvalue; (int = 0; < numlength; i++) { for(int j = 0; j < numlength; j++) { nsnumber *temp=[array objectatindex:i]; int first =[temp integervalue]; nsnumber *temp1=[array objectatindex:j+1]; int second =[temp1 integervalue]; if(first > second) { tempvalue = second; [array replaceobjectatindex:j+1 withobject:temp]; [array replaceobjectatindex:i withobject:temp1]; } } } nslog(@"array %@", array);
this code in viewdidload...
thanks
try this, works indeed:
nsmutablearray *_array = [nsmutablearray array]; (int = 0; < 5; i++) { [_array addobject:@(arc4random()%10)]; } nslog(@"random: %@", _array); (int = 0; < _array.count; i++) { for(int j = i; j < _array.count; j++) { if (i != j) { nsinteger _first = [[_array objectatindex:i] integervalue]; nsinteger _second = [[_array objectatindex:j] integervalue]; if (_second < _first) { [_array exchangeobjectatindex:i withobjectatindex:j]; } } } } nslog(@"sorted : %@", _array);
note: way sort array's elements highly inefficient, recommended use educational purpose.
Comments
Post a Comment