现有一个数组NSMutableArray, 数组有若干个NSString的元素,进行选择法排序

 // 参数arr 表示数组对象地址
 //参数 asc=YES 表示升序 asc=NO 表示降序

-(void)selectionSort:(NSMutableArray *)arr andAsc:(BOOL)asc
{
    
       if (asc==NO) {
        for (int i=0; i<arr.count; i++) {
            for (int j=i+1; j<arr.count; j++) {
                if ([arr[i]isLessThan:arr[j]]) {
                    NSString *str=arr[i];
                    arr[i]=arr[j];
                    arr[j]=str;
                }

            }
                        }
        NSLog(@"%@",arr);
        }
    //no降序//yes升序
    else if(asc==YES)
    {
        for (int i=0; i<arr.count; i++) {
            for (int j=i+1; j<arr.count; j++) {
                NSComparisonResult retstr=[arr[i] compare:arr[j]];
                if (retstr==NSOrderedDescending) {
                    NSString *str=arr[i];
                    arr[i]=arr[j];
                    arr[j]=str;
                }
            }
            
        }
        NSLog(@"%@",arr);
    }
    else
    {NSLog(@"输入有误");}
}
+(void)test
{
    NSMutableArray *ary=[[NSMutableArray alloc]initWithObjects:@"aa",@"bne",@"cwo",@"dd",@"ehree",@"four", nil];
    BOOL ret=YES;
    NSLog(@"升序");
    Releven *elev=[[Releven alloc]init];
    [elev selectionSort:ary andAsc:ret];
    NSLog(@"降序");
    ret=NO;
    [elev selectionSort:ary andAsc:ret];
}

posted @ 2015-06-19 09:04  天使雨儿  阅读(230)  评论(0编辑  收藏  举报