2013-02-06 115 views
-2

你們可以請幫我在C#中進行基本的插入排序。我有一個名單和一個數組中的居住城市,需要通過比較居住城市來對這個數組進行排序。列表必須按字母順序排序。比較器已經建立並運行我只是因爲插入分類器編程而失去了知識,因爲這是我們第一次採用這種分類方法。插入排序c#

這裏是我試過到目前爲止:

public void InsertionSort() 
{ 
    for (int i = 0; i < Count; i++) 
    { 
     Student cur = Attendees[i]; 
     for (int j = 0; j < Count; j++) 
     { 
      Student Sel = Attendees[j]; 
      if (cur.CompareTo(Sel) < 0) 
      { 
       Student temp = Attendees[j]; 
       Attendees[j] = Attendees[i]; 
       for (int k = i; k > j; k--) 
        Attendees[k] = Attendees[k - 1]; 
       Attendees[k + 1] = temp; 
      } 
     } 
    } 
} 
+0

步驟:1-編輯你的問題。 2-發佈一些嘗試/代碼。結果:獲得較少的提議+獲得答案/建議。 – AbZy

+0

谷歌是你的朋友!這是一個射擊:http://www.csharp-examples.net/sort-array/ – Jocke

+1

public void InsertionSort() { for(int i = 0; i j; k--) (參數: 參加者[k + 1] = temp; – user2046257

回答

4

嘗試像這樣...

public void InsertionSort() 
{ 
    for (int i = 0; i < Count; i++) 
    { 
     int j = i; 
     While(j > 0) 
     { 
      Student cur = Attendees[j]; 
      Student sel = Attendees[j-1]; 
      if (cur.CompareTo(Sel) < 0) 
      { 
       Student temp = cur; 
       cur = sel; 
       sel = temp; 
       j-- 
      } 
      else 
       break; 
     } 
    } 
} 
+1

非常感謝:)幫助很多,代碼現在工作:) – user2046257

3
public void InsertionSort() 
{ 
    for (int i = 1; i < Count; i++) // Iterate beginning at 1, because we assume that 0 is already sorted 
    { 
     for (int j = i; j > 0; j--) // Iterate backwards, starting from 'i' 
     { 
      Student cur = Attendees[j - 1]; 
      Student tbs = Attendees[j]; // 'tbs' == "to be sorted" 
      if (cur.CompareTo(tbs) < 0) // usually, classes that implement 'CompareTo()' also implement 'operator <()', 'operator >()' and 'operator ==()', so you could have just written 'cur < tbs' 
      { 
       Student temp = Attendees[j]; 
       Attendees[j] = Attendees[j - 1]; 
       Attendees[j - 1] = temp; 
      } 
      else 
       break; // since 'tbs' is no longer > 'cur', it is part of our sorted list. We don't need to sort that particular 'tbs' any further 
     } 
    } 
} 

請記住,該算法排序的降序排列列表。

0

int[] newarr = {2,1,5,3,7,6}; int a, b; for (int i = 1; i < newarr.Length; i++) { a = newarr[i]; b = i - 1; while(b>=0 && newarr[b]>a) { newarr[b+1] = newarr[b]; b=b-1; } newarr[b+1] = a; }