C语言数组插入排序:将数据插入降序排列数组
C语言数组插入排序:将数据插入降序排列数组
问题描述:
定义函数 void fun(int *p, int num),将数据 num 插入在指针 p 所指向的数组中,主函数中定义并初始化一个降序排列的数组 a[10]={86,81,78,68,45,35},输入整数 num,调用函数完成插入操作,输出插入数据后的数组,输出格式:"%d "
要求:
插入完成后,数组仍按降序排列。
输入形式:
num
输出形式:
插入后数组
样例输入:
15
样例输出:
86 81 78 68 45 35 15
解题思路:
- 先找到
num需要插入的位置,即第一个小于num的元素位置,假设为pos。 - 从数组尾部开始,将
pos到最后位置的元素依次后移一位。 - 将
num插入到pos位置。
注意:
在寻找 pos 位置时,需要特判 num 比数组中所有元素都小或比数组中所有元素都大的情况。
参考代码:
#include <stdio.h>
void fun(int *p, int num) {
int pos = 0;
int i;
// 找到插入位置
while (pos < 10 && p[pos] >= num) {
pos++;
}
// 若 num 比数组中所有元素都小
if (pos == 10) {
pos = 9;
}
// 从数组尾部开始,将 pos 到最后位置的元素依次后移一位
for (i = 9; i > pos; i--) {
p[i] = p[i - 1];
}
// 将 num 插入到 pos 位置
p[pos] = num;
}
int main() {
int a[10] = {86, 81, 78, 68, 45, 35};
int num;
// 输入整数 num
scanf("%d", &num);
// 调用函数 fun 完成插入操作
fun(a, num);
// 输出插入数据后的数组
for (int i = 0; i < 10; i++) {
printf("%d ", a[i]);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/omab 著作权归作者所有。请勿转载和采集!