插入排序功能不起作用。为什么?

时间:2019-02-15 10:38:26

标签: c

void insertionsort(int a[], int n){
    int next, i, j;
    for(i=1; i<n; i++){
        if(a[i]<a[i-1]){
            for(j=i-2; j>=0; j--){
                if(a[j]<a[i]){
                    next = a[i];
                    a[i] = a[j];
                    a[j] = next;
                }
            }
        }
    }
}

此函数应按递增顺序对数组的元素进行排序。为什么不起作用?

2 个答案:

答案 0 :(得分:1)

您的解决方案与算法说明的不完全相同。您可能会考虑不使用 两个嵌套的for循环:

void insertionsort(int a[], int n){
   int i, key, j; 
   for (i = 1; i < n; i++) 
   { 
       key = a[i]; 
       j = i-1; 

       /* 
          Move all elements in the array at index 0 to i-1, that are 
          greater than the key element, one position to the right 
          of their current position 
       */
       while (j >= 0 && a[j] > key) 
       { 
           a[j+1] = a[j]; 
           j = j-1; 
       } 
       a[j+1] = key; 
   } 
}

答案 1 :(得分:0)

您还需要交换i-1索引值,并且第二个for循环条件应为>

void insertionsort(int a[], int n){
    int next, i, j;
    for(i=1; i<n; i++){
        if(a[i]<a[i-1]){
            for(j=i; j>0; j--){
                if(a[j - 1]>a[ j ]){
                    next = a[ j - 1];
                    a[j - 1] = a[j];
                    a[j] = next;
                }
            }
        }
    }
}