插入排序c#

你能帮我们用C#进行基本的插入排序吗? 我有一个列表中的名称和居住城市列表,需要通过比较居住城市对该arrays进行排序。 列表必须按字母顺序排序。 比较器已经设置和工作我只是有点丢失与插入分拣机编程,因为这是我们第一次做这种排序方法。

这是我到目前为止所尝试的内容:

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)  j; k--) Attendees[k] = Attendees[k - 1]; Attendees[k + 1] = temp; } } } } 

试试这样……

 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; } } } 
 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 } } } 

请记住,此算法按降序对列表进行排序。

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; }