排序之c与oc比较

1、插入法 c写法:

void insertSort(int a[ ], int n)
{
    int i,j,p;
    for (i = 1; i<n; i++)
    {        
        t=a[ i ];
        for( j = i-1;  j >= 0;  j--)
        {
            if( t < a[ j ] )
            { 
                a[ i ] = a[ j ];
                a[ j ] = t;
            }//if
        }//for2
    }//for1

    //打印需要遍历
    printf("element of array is:");
    for( int t = 0; t<n; t++)
    {
           printf("%d," a[t]);
    }
}

2、选择法OC写法:

- (void)swapWithData:(NSMutableArray *)aData index1:(NSInteger)index1 index2:(NSInteger)index2
{
     NSNumber *tmp = [aData objectAtIndex:index1];
    [aData replaceObjectAtIndex:index1 withObject:[aData objectAtIndex:index2]];
    [aData replaceObjectAtIndex:index2 withObject:tmp];
}

- (void)sortWithArray:(NSArray *)aData
{
    NSMutableArray *data =[[[NSMutable Array] alloc] initWithArray:aData];
    for (int i = 0; i<[data count] -1; i++)
    {
        int m = i;
        if([data objectAtIndex:j] < [data objectAtIndex:m])
            m = j;
        if (m != i)
            [self swapWithData:data index1:m index2:i];
     }
    //打印是无需使用for循环
    NSLog(@"选择排序后结果为%@", [data description];
    [data release];
}

比较我们可以看出,c更简洁,oc更容易看懂; 另外oc可以使用c, c确不能使用oc,oc更灵活;

下面是一个使用Objective-C语言实现的快速排序算法的示例代码: ```objective-c #import <Foundation/Foundation.h> void swap(NSMutableArray *array, NSInteger index1, NSInteger index2) { id temp = array[index1]; array[index1] = array[index2]; array[index2] = temp; } NSInteger partition(NSMutableArray *array, NSInteger low, NSInteger high) { // 选择数组中的最后一个元素作为基准值 id pivot = array[high]; // 将小于基准值的元素放在左边,大于基准值的元素放在右边 NSInteger i = low - 1; for (NSInteger j = low; j <= high - 1; j++) { if ([array[j] compare:pivot] == NSOrderedAscending) { i++; swap(array, i, j); } } swap(array, i + 1, high); return i + 1; } void quickSort(NSMutableArray *array, NSInteger low, NSInteger high) { if (low < high) { NSInteger pivotIndex = partition(array, low, high); // 对基准值左边的子数组进行快速排序 quickSort(array, low, pivotIndex - 1); // 对基准值右边的子数组进行快速排序 quickSort(array, pivotIndex + 1, high); } } int main(int argc, const char * argv[]) { @autoreleasepool { NSMutableArray *array = [NSMutableArray arrayWithObjects:@5, @3, @8, @4, @2, nil]; // 调用快速排序算法对数组进行排序 quickSort(array, 0, array.count - 1); // 输出排序后的结果 NSLog(@"%@", array); } return 0; } ``` 这段代码使用了递归的思想来实现快速排序。首先,选择数组中的最后一个元素作为基准值,然后将小于基准值的元素放在左边,大于基准值的元素放在右边。然后,对基准值左边和右边的子数组分别进行递归调用,直到子数组的长度为1或0时停止递归。最终,通过不断交换元素的位置,实现了对数组的快速排序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

群野

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值