2010-12-18 34 views
1

這段代碼給出了輸出,但它有一個問題,即當用戶在textbox1中寫入5,6和在textbox3中輸出時,它輸出5,6。我知道問題是當元素一個數組結束,它不打印其他數組的其餘元素,我評論了問題的線。合併排序算法的輸出問題

編輯:我用TextBox1中和textbox3用於獲取用戶要合併

private void button3_Click(object sender, EventArgs e) 
{ 


    string[] source = textBox1.Text.Split(','); 
    string[] source1 = textBox3.Text.Split(','); 
    int[] nums2 = new int[8]; 
    int[] nums = new int[source.Length]; 
    for (int i = 0; i < source.Length; i++) 
    { 
     nums[i] = Convert.ToInt32(source[i]); 

    } 
    int[] nums1 = new int[source1.Length]; 
    for (int j = 0; j < source1.Length; j++) 
    { 
     nums1[j] = Convert.ToInt32(source1[j]); 
    } 
    int x = 0; 
    int y = 0; 
    int z = 0; 

    while (x < nums.Length && y < nums1.Length) 
    { 
     if (nums[x] < nums1[y]) 
     { 
      nums2[z] = nums[x]; 
      x++; 

     } 
     else 
     { 
      nums2[z] = nums1[y]; 
      y++; 
     } 

     z++; 
    }////----->>it works untill here 

    while (x > nums.Length)///this mean when the elements of nums end,out the rest of the elements in other textbox but it doesnt do anything,whats the problem ? 
    { 
     if (y <= nums1.Length) 
     { 
      nums2[z] = nums1[y]; 

      z++; 
      y++; 
     } 
    } 
    while (y > nums1.Length) 
    { 

     if (x <= nums.Length) 
     { 
      nums2[z] = nums[x]; 
      z++; 
      x++; 
     } 
    } 
     string merge = ""; 
     foreach (var n in nums2) 
      merge += n.ToString() + ","; 
     textBox4.Text = merge; 


    } 
+4

mergesort,textboxes,你在說什麼? mergesort中不存在stinkin'texboxes! – 2010-12-18 15:48:19

+0

我用textbox1和textbox3獲取用戶想要合併的數組元素 – Arash 2010-12-18 15:52:58

+1

不,這不是比你以前的重複問題更清晰:http://stackoverflow.com/questions/4477248/problem-with-mergesort -algorithm-in-c – 2010-12-18 15:53:27

回答

1

DO(刪除你的最後一段時間)

while (x < nums.Length) 
{ 
     nums2[z] = nums[x]; 
     z++; 
     x++; 
} 

while (y < nums1.Length) 
{ 
     nums2[z] = nums1[y]; 
     z++; 
     y++; 
} 

,因爲你不知道哪個數組項目依然存在,還您當前的代碼不反正工作,因爲Y不相關NUMS和老虎鉗詩句。

編輯︰我複製過去第一次,同時,修復它,刪除你最後的while循環(2,而如果在他們),並取而代之。

+0

它給出了運行時錯誤:索引超出了範圍 – Arash 2010-12-18 16:08:01

+0

最後一個塊應該使用y而不是的x作爲nums1的索引。 – BlueMonkMN 2010-12-18 16:45:35

+0

@arash,修復它,@BlueMonkMN,是的我修復它,我先複製粘貼,而忘記第二個循環的內容。 – 2010-12-18 16:54:12

1

無論你對while (x > nums.Length)while (y > nums1.Length)條件沒有意義的數組的元素,因爲這永遠不會發生。

在塊之前,你增加xy只要他們比nums.Lengthnums1.Length。因此,這些永遠不會變大(最多相等),因此這兩個條件將始終是錯誤的,並且「剩餘」項不會合並。

請注意,您的mergesort實現中還存在其他錯誤,但這不是在我想你的具體問題的範圍內。