合并有序数组

来源:互联网 发布:win8rt软件下载 编辑:程序博客网 时间:2024/04/28 00:37
  1. public class ArraySort {    
  2.     
  3.     public static void main(String[] args) {    
  4.         int[] a = {1,3,4};    
  5.         int[] b = {2,3,5,6};    
  6.             
  7.         int[] c = mergeArray(a, b);    
  8.             
  9.         for(int n : c){    
  10.             System.out.print(n+" ");    
  11.         }    
  12.     }    
  13.         
  14.     //合并数组    
  15.     public static int[] mergeArray(int[] a , int[] b){    
  16.         int result[] = new int[a.length + b.length];    
  17.             
  18.         if(checkSort(a) && checkSort(b)){    
  19.             //说明ab数组都是有序的数组    
  20.             //定义两个游标    
  21.             int i=0,j=0,k=0;    
  22.                 
  23.             while(i<a.length && j<b.length){    
  24.                 if(a[i] <= b[j]){    
  25.                     result[k++] = a[i++];    
  26.                 }else{    
  27.                     result[k++] = b[j++];    
  28.                 }    
  29.             }    
  30.                 
  31.             while(i < a.length){    
  32.                 //说明a数组还有剩余    
  33.                 result[k++] = a[i++];    
  34.             }    
  35.                 
  36.             while(j < b.length){    
  37.                 result[k++] = b[j++];    
  38.             }    
  39.         }    
  40.             
  41.         return result;    
  42.             
  43.     }    
  44.         
  45.     //检查一个数组是否是有序的    
  46.         
  47.     // 1 2 3    
  48.     public static boolean checkSort(int[] a){    
  49.         boolean flag = false;//默认不是有序的    
  50.             
  51.         for(int i=0;i<a.length-1;i++){    
  52.             if(a[i] > a[i+1]){    
  53.                 //说明不是有序的    
  54.                 flag = false;    
  55.                 break;    
  56.             }else{    
  57.                 flag = true;    
  58.             }    
  59.         }    
  60.             
  61.         return flag;    
  62.     }    
  63. }    
0 0
原创粉丝点击