Removing Duplicates Inside Insertion Sort

回眸只為那壹抹淺笑 提交于 2019-12-01 00:37:40

You only need to add a single line to your while loop.

while (j > 0 && temp <= a[j - 1]) {
    if(temp == a[j - 1]) temp = -1;
    a[j] = a[j - 1];

    j--;
}

You can think of the array as having two parts. The first part goes from 0 to i-1 and is sorted. The second part goes from i to the end of the array and is unsorted. In each iteration of the loop you take the first of the unsorted elements (which is a[i]) and place it into temp. This is the element you want to insert into the sorted part. Then you shift all the elements of the sorted part up until you find the place to insert temp. If you change temp to -1, your element that you are trying to insert now has become -1. The sorting algorithm will go on to try and insert -1 at the right place, which is the beginning of the array.

public void InsertSort()
{
    int t, j;
    for (int i = 1; i < _leght; i++)
    {
       t = _arr[i];
       for (j = i; j > 0; )
       {
            if (_arr[j - 1] == t) t = -1;
            if (_arr[j - 1] > t)
            {
                  _arr[j] = _arr[j - 1];
                  j--;
             }
             else break;
        }
        _arr[j] = t;
     }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!