您现在的位置是:首页 > 博客日记 > Web前端 Web前端

三个有序数据 var a=[2,3,4,5,6,9,10], b=[6,9,10,11,13,15], c=[2,3,4,7,9,10]; 存储合并后的数组

2019-09-09 14:41:39

  1. //三个有序数据
  2. var a=[2,3,4,5,6,9,10], b=[6,9,10,11,13,15], c=[2,3,4,7,9,10];
  3. //存储合并后的数组
  4. var d=[],len = 0;
  1. //第一步
  2. for(var i=0,j=0,k=0;i<a.length && j<b.length && k<c.length;){
  3. var aValue = a[i];
  4. var bValue = b[j];
  5. var cValue = c[k];
  6. if(aValue <= bValue && aValue <= cValue){
  7. d[len++] = aValue;
  8. i++;
  9. }else if(bValue <= cValue && bValue <= cValue){
  10. d[len++] = bValue;
  11. j++;
  12. }else if(cValue <= aValue && cValue <= bValue){
  13. d[len++] = cValue;
  14. k++;
  15. }
  16. }
  17. console.log(d);
  18. //第二步
  19. if(i == a.length){
  20. for(;j<b.length && k<c.length;){
  21. var bValue = b[j];
  22. var cValue = c[k];
  23. if(bValue <= cValue){
  24. d[len++] = bValue;
  25. j++;
  26. }else{
  27. d[len++] = cValue;
  28. k++;
  29. }
  30. }
  31. }else if(j == b.length){
  32. for(;i<a.length && k<c.length;){
  33. var aValue = a[i];
  34. var cValue = c[k];
  35. if(aValue <= cValue){
  36. d[len++] = aValue;
  37. i++;
  38. }else{
  39. d[len++] = cValue;
  40. k++;
  41. }
  42. }
  43. }else if(l == c.length){
  44. for(;i<a.length && j<b.length;){
  45. var aValue = a[i];
  46. var bValue = b[j];
  47. if(aValue <= cValue){
  48. d[len++] = aValue;
  49. i++;
  50. }else{
  51. d[len++] = bValue;
  52. j++;
  53. }
  54. }
  55. }
  56. console.log(d);
  57. //第三步
  58. if(i<a.length){
  59. for(;i<a.length;i++){
  60. d[len++] = a[i];
  61. }
  62. }else if(j<b.length){
  63. for(;j<b.length;j++){
  64. d[len++] = b[j];
  65. }
  66. }else if(k<c.length){
  67. for(;k<c.length;k++){
  68. d[len++] = c[k];
  69. }
  70. }
  71. console.log(d);


关注TinyMeng博客,更多精彩分享,敬请期待!