Sorting Array in increasing order

前端 未结 7 426
鱼传尺愫
鱼传尺愫 2021-01-03 07:01

I have an array that contains values like 0,3,2,8 etc.I want to sort my array in increasing order.Please tell me how to do this.

Thanks in advance!!

相关标签:
7条回答
  • 2021-01-03 07:30

    If your array is an NSArray containing NSNumbers:

    NSArray *numbers = [NSArray arrayWithObjects:
                        [NSNumber numberWithInt:0],
                        [NSNumber numberWithInt:3],
                        [NSNumber numberWithInt:2],
                        [NSNumber numberWithInt:8],
                        nil];
    
    NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES selector:@selector(localizedCompare:)];
    NSArray *sortedNumbers = [numbers sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    

    Keep in mind though, that this is just one way to sort an NSArray.

    Just to name a few other methods of NSArray:

    • sortedArrayHint
    • sortedArrayUsingFunction:context:
    • sortedArrayUsingFunction:context:hint:
    • sortedArrayUsingDescriptors:
    • sortedArrayUsingSelector:
    • sortedArrayUsingComparator:
    • sortedArrayWithOptions:usingComparator:

    If your array is a c int array containing ints:

    #include <stdio.h>
    #include <stdlib.h>
    int array[] = { 0, 3, 2, 8 };
    int sort(const void *x, const void *y) {
        return (*(int*)x - *(int*)y);
    }
    void main() {
        qsort(array, 10, sizeof(int), sort);
    }
    
    0 讨论(0)
提交回复
热议问题