merge sort not working

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Feb 2008
Posts: 7
Reputation: TSharma is an unknown quantity at this point 
Solved Threads: 1
TSharma TSharma is offline Offline
Newbie Poster

merge sort not working

 
0
  #1
Feb 9th, 2008
i am trying out merge sort.
i have made two functions sort and merge;
i am calling merge recursively.
i think my sort function is working fine. the problem lies with merge function.
in merge function i am dividing the array using recursive calls. it ends when lb = = ub(ie lower bound equals upper bound). lower bound and upper bound are index of array.

then i am passing it to sort function function.

suggest me a solution of correction to merge sort.

  1.  
  2. #include<iostream>
  3. //#include<stream>
  4.  
  5. using namespace std;
  6.  
  7. int A[7] = {3,4,77,10,2,5,7};
  8.  
  9. void sort(int l1,int u1,int l2,int u2)
  10. {
  11. int B[7];
  12. int i=l1;
  13. int j=l2;
  14. int k=0;
  15.  
  16. while(i<=u1&&j<=u2) {
  17. if(A[i]<A[j]) {
  18. B[k] = A[i];
  19. i++;
  20. k++;
  21. }
  22.  
  23. else {
  24. B[k] = A[j];
  25. j++;
  26. k++;
  27. }
  28. }
  29.  
  30.  
  31. while(j<=u2) {
  32. B[k]=A[j];
  33. j++;
  34. k++;
  35. }
  36.  
  37. while(i<=u1) {
  38. B[k] = A[i];
  39. i++;
  40. k++;
  41. }
  42.  
  43. for(i=l1;i<=u2;i++){
  44. A[i]=B[i];
  45. }
  46. }
  47.  
  48.  
  49.  
  50.  
  51.  
  52. void merge(int lb,int ub)
  53. {
  54. int lo;
  55. lo=(ub+lb)/2;
  56.  
  57. if(lb<ub){
  58. merge(lb,lo);
  59. merge(lo+1,ub);
  60. sort(lb,lo,lo+1,ub);
  61. }
  62. }
  63.  
  64.  
  65. int main()
  66. {
  67. for(int i=0;i<7;i++)
  68. cout<<A[i]<<" ";
  69. cout<<endl;
  70.  
  71. merge(0,6);
  72. //sort(0,3,4,6);
  73. for(int i=0; i<7;i++)
  74. cout<<A[i]<<" ";
  75.  
  76. return 0;
  77. }
Reply With Quote Quick reply to this message  
Join Date: Feb 2008
Posts: 4
Reputation: wouterdc is an unknown quantity at this point 
Solved Threads: 0
wouterdc wouterdc is offline Offline
Newbie Poster

Re: merge sort not working

 
0
  #2
Feb 9th, 2008
I don't think it is your merge function but the sort function.
You're starting to fill in B in the beginning but you have to start at l1.
So the inititial value for k has to be l1, not zero.
Reply With Quote Quick reply to this message  
Join Date: Feb 2008
Posts: 7
Reputation: TSharma is an unknown quantity at this point 
Solved Threads: 1
TSharma TSharma is offline Offline
Newbie Poster

Re: merge sort not working

 
0
  #3
Feb 13th, 2008
Thanks i just got what is wrong!
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC