2012-04-06 70 views
-4

我排序的代碼不給正確的結果,它沒有正確sortint給定的名單,而我沒有得到錯誤,請檢查一下,氣泡排序不正確的結果代碼附加C#?

static void Main(string[] args) 

     { 

      List<int> a = new List<int>(new int[] { 3, 7, 6, 1, 8, 5 }); 

      int temp; 

// foreach(int i in a) 

for(int i=1; i<=a.Count; i++) 

for(int j=0; j<a.Count-i; j++) 

if (a[j] > a[j + 1]) 

{ 

temp = a[j]; 

a[j] = a[j + 1]; 

a[j + 1] = temp; 

Console.WriteLine(a[j]); 


} 

Console.Read(); 

} 
+5

這不是代碼評論網站。 [FAQ](http://stackoverflow.com/faq#questions) – Reniuz 2012-04-06 07:40:30

+2

謹慎格式化您的代碼? – 2012-04-06 07:40:58

+2

您的代碼*確實對輸入進行了正確排序。但是'Console.WriteLine'調用與此無關。 – 2012-04-06 07:47:32

回答

0

你貼什麼不是Bubble Sort algorithm的實現。你忘了循環,而沒有數字交換了。這是一個氣泡排序實現,編寫爲by John Skeet。該stillGoing檢查是什麼,至少在你的實現是缺少:

public void BubbleSort<T>(IList<T> list); 
{ 
    BubbleSort<T>(list, Comparer<T>.Default); 
} 

public void BubbleSort<T>(IList<T> list, IComparer<T> comparer) 
{ 
    bool stillGoing = true; 
    while (stillGoing) 
    { 
     stillGoing = false; 
     for (int i = 0; i < list.Length-1; i++) 
     { 
      T x = list[i]; 
      T y = list[i + 1]; 
      if (comparer.Compare(x, y) > 0) 
      { 
       list[i] = y; 
       list[i + 1] = x; 
       stillGoing = true; 
      } 
     } 
    } 
} 
2

我無法理解你的代碼,我不知道C#。但無論如何,這裏是氣泡排序的排序邏輯(用c編寫)。

//assuming there are n elements in the array a[] 

    for(i=0; i<n; i++) 
    { for(j=1; j<n-i; j++) 
     { if(a[j] < a[j-1]) 
      { temp = a[j]; 
       a[j] = a[j-1]; 
       a[j-1] = temp; 
      } 
     } 
    } 

,你也可以參考: www.sorting-algorithms.com/bubble-sort

0

從嵌套循環刪除console.write。將嵌套循環外的console.write放在新的for循環或foreach中。 然後你會得到正確的順序。否則,冒泡排序的邏輯是正確的