力扣刷题-324.摆动排序 II

题目

题解

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

int cmp(const void *a, const void *b){
    return *(int*)a - *(int*)b;
}

int main(){
    int numsSize;
    cin>>numsSize;
    if(numsSize == 0){
        return NULL;
    }
    int* nums = (int*)malloc(sizeof(int)*numsSize);
    for(int i = 0; i < numsSize; i++){
        cin>>nums[i];
    }
    qsort(nums,numsSize,sizeof(int),cmp);
    int small = numsSize / 2 + numsSize % 2;
    int* result = (int*)malloc(sizeof(int)*numsSize);
    int index = 0;
    for(int i = 0;i < numsSize; i++){
        result[i] = nums[i];
    }
    for(int i = small-1; i >= 0; i--){
        nums[index] = result[i];
        index += 2;
    }
    index = 1;
    for(int i = numsSize-1;i >= small; i--){
        nums[index] = result[i];
        index += 2;
    }
    for(int i = 0; i < numsSize; i++){
        cout<<nums[i]<<endl;
    }
    return 0;
}

要点

  1. 使用stalib头文件中的qsort函数时,第一个参数是数组的首地址,第二个参数是数组长度,第三个参数是数组单位长度,第四个参数是比较函数。

  1. 比较函数写法固定。两参数为const void *指针类型。递增是第一个指针减第二个指针。

int cmp(const void *a, const void *b){
    return *(int*)a - *(int*)b;
}
  1. 本题要点在于将序列分成较大/较小两个序列,然后再将较大的序列中的每一个依次插入较小的序列中。注意,较小的序列和较大的序列都要逆序从大到小排序。

举例如4,5,6,5。
1.先按从小到大排列:4,5,5,6。
2.将其从中间分为两个序列:4,5;5,6。
3.两个序列分别从大到小排序:5,4;6,5。
4.将较大序列插入到较小的序列中:5,6,4,5。
若不将两个从大到小排序会出现以下状况,不符合要求:
4,5,5,6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

东东咚咚东

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

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

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

打赏作者

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

抵扣说明:

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

余额充值