[数据结构]合并有序数组
生活随笔
收集整理的這篇文章主要介紹了
[数据结构]合并有序数组
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 10C語言版
#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 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的[数据结构]合并有序数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NavigationBar 渐隐效果
- 下一篇: spring BeanFactory加载