数组数据分类

实现一个函数,把如下数组中非零的数放在左边,0数放在右边,函数参数为数组和数组长度。
例如
arr[7] = {0, 10, 3, 2, 0, 2, 0};
分类后结果为
10, 3, 2, 2, 0, 0, 0

 

#include <stdio.h>

static int find_next_zero_postion(int* a, int start_idx, int end_idx)
{
    while(start_idx < end_idx)
    {
        if(0 == a[start_idx])
        {
            break;
        }
        start_idx++;
    }

    return start_idx;
}

static int find_next_data_postion(int* a, int start_idx, int end_idx)
{
    while(start_idx < end_idx)
    {
        if(0 != a[start_idx])
        {
            break;
        }
        start_idx++;
    }

    return start_idx;
}

static void print_array(int* a, int len)
{
    int i;
    for(i=0; i<len; i++)
    {
        // printf("%d = %d \n", i, a[i]);
        printf("%04d ", a[i]);
    }
    printf("\n");

}

void classify_num_and_zero(int* a, int len)
{
    int i;
    int zero_idx = 0;
    int data_idx = 0;

    zero_idx = find_next_zero_postion(a, 0, len);
    for(i=0; i<len; i++)
    {
        zero_idx = find_next_zero_postion(a, zero_idx, len);
        if(zero_idx >= len)
        {
            break;
        }
        data_idx = find_next_data_postion(a, zero_idx, len);
        if(data_idx >= len)
        {
            break;
        }

        i = zero_idx;
        a[zero_idx] = a[data_idx];
        a[data_idx] = 0; 
        
    }

}

int main(void) {
    // int a[10] = {0,2,3,-1,-1,1,0,6,-10,20};
    int a[3] = {1,0,1};
    print_array(a, sizeof(a)/sizeof(a[0]));
    classify_num_and_zero(a, sizeof(a)/sizeof(a[0]));
    print_array(a, sizeof(a)/sizeof(a[0]));
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值