arrays - 在数组中添加多个元素
问题描述
#include <stdio.h>
int main () {
int []={1,2,3,7,8}; // add element after 3 --> 4,5,6 (condition that i don't know position of 3 in array)
for(int i=0,i<10;i++)
{
printf("%d\n",n[i]);
}
return 0;
}
我想要输出 1,2,3,4,5,6,7,8 但请记住以防我不知道数组中 3 或 7 的位置
解决方案
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
// n = len of tab
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
int main()
{
int len = 10;
int top_number_count = 3;
int data[10] = {1, 11, 3, 4, 5, 20, 7, 8, 9, 10};
int temp[10];
// copy the tab for dont change any value
for (int i = 0; i < len; i++) {
temp[i] = data[i];
}
// sort the new tab
bubbleSort(temp, len);
// print the top number
// top_number_count is the count of max number you want
for (int i = len - top_number_count; i < len; i++)
printf(">%d\n", temp[i]);
return 0;
}
推荐阅读
- java - 如何通过带有 HATEOAS 的 @JoinTable 获取信息
- node.js - MQTT 订阅者是否需要静态 IP?
- c# - 为什么我的 WebAPI 服务调用无法通过 IIS 找到文件夹路径的一部分?
- c++ - 具有范围的随机数生成器?C++
- python - 理解 TensorFlow 中的 ResourceVariables
- python - 如何对我的软件进行编程以将其数据保存到特定服务器?
- docker - Docker Alpine dotnet Core 2.2 Console App 每个响应内容长度 0
- c# - 选择要在启动时自动迁移的 DbContext
- javascript - ng2-smart-table 如何更改自定义按钮在单击时显示和隐藏
- javascript - 谷歌放置国家代码和谷歌搜索