当前位置: 首页 > news >正文

[数据结构]合并有序数组

JAVA版

public class Merge {//合并有序数组public static void mergeSort(int a[], int b[], int c[]) {int n = a.length, m = b.length;int i, j, k;i = j = k = 0;while (i < n && j < m) {if (a[i] < b[j]) {c[k++] = a[i++];} else {c[k++] = b[j++];}}while (i < n)c[k++] = a[i++];while (j < m)c[k++] = b[j++];}//打印数组中的元素public static void printArr(int a[]) {for (int i = 0; i < a.length; i++) {System.out.print(a[i] + "\t");}}public static void main(String[] args) {System.out.println("Hello World!");int[] a = new int[] { 1, 2, 5, 6 };int[] b = new int[] { 3, 8, 9, 10 };int c[] = new int[8];mergeSort(a, b, c);printArr(c);}
}
输出结果:
1   2   3   5   6   8   9   10

C语言版

#include <stdio.h>
// 打印数组a
void printArr(int a[],int n){for (int i = 0; i < n; ++i){printf("%d\t",a[i]);}printf("\n");
}
//合并有序数组
void  mergeArray(int a[],int n,int b[],int m,int c[]){int i, j, k;  i = j = k = 0;  while (i <n && j<m)  {  if (a[i] < b[j])  c[k++] = a[i++];  else  c[k++] = b[j++];   }  while (i < n)  c[k++] = a[i++];  while (j < m)  c[k++] = b[j++];  }
int main(){int a[3]={2,3,6};int b[2]={1,5};int c[5]={};mergeArray(a,3,b,2,c);printArr(c,5);
}
输出结果:
yaopans-MacBook-Pro:algorithm yaopan$ ./a.out 
1   2   3   5   6

http://www.taodudu.cc/news/show-854181.html

相关文章:

  • mobarxtem应用与华为设备端口绑定技术
  • ICode国际青少年编程竞赛- Python-3级训练场-坐标判断1
  • itextpdf 7生成pdf(主要是文字和表格,支持中文)
  • 生产透明化,交付无烦恼
  • 【AI学习】聊两句昨夜OpenAI的GPT-4o
  • WEB前端复习——JS
  • spring BeanFactory加载xml配置文件示例
  • nginx location配置详解
  • 三星1TB硬盘MM804RS不识别加电磁头打盘敲盘异响不识别开盘恢复数据
  • Zookeeper Learning
  • 浑浑噩噩工作已多年
  • log4j+logback+slf4j+commons-logging的关系与调试
  • 使用 rem 实现 适配各种屏幕布局
  • 设计模式Adapter模式的五分钟
  • oracle的SCN和Checkpoint_Change#的关系
  • A problem while linking c++ to python
  • 几大基础算法
  • POPTEST学员就业面试题目!!!!!
  • 【自定义控件】自定义属性
  • 我的Git使用-资料查询,名博笔记
  • firefox-Developer开发者站点——关于Object.create()新方法的介绍
  • SharePoint 使用脚本为表单绑定事件
  • 解决Cannot change version of project facet Dynamic Web M
  • Github博客地址
  • c language compile process.
  • 阅读总结:如何在生产中成功运用Docker
  • [搜索]Trie树的实现
  • 老李分享:接口测试之jmeter
  • maven远程发布jar
  • GPRS模块AT呼叫控制命令
  • hadoop datanode启动失败
  • CentOS6.5下用yum安装 git .
  • 读博文学Android
  • javaWEB学习之filter
  • mysql字符集调整总结
  • C#ListBox对Item进行重绘,包括颜色