Insertion Sorting c#

前端 未结 3 765
暗喜
暗喜 2021-01-29 12:10

Can you guys please help me with basic insertion sorting in C#. I have a list of names and city of residence in a array and need to sort this array by comparing the city of resi

相关标签:
3条回答
  • 2021-01-29 12:44
    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;
    }
    
    0 讨论(0)
  • 2021-01-29 12:54

    Try like this...

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-29 13:02
    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
            }
        }
    }
    

    Keep in mind, that this algorithm sorts your list in descending order.

    0 讨论(0)
提交回复
热议问题