-1

这是我的代码:

#include <stdio.h>
#define SIZE 4
int main(int argc, const char * argv[])
{
double m[SIZE],tmp;
int i,min,max,c,k,l,pos;
for (i=0; i<SIZE; i++) {
    printf("a%d? ",i);
    scanf("%lf",&m[i]);
}
for (i=0; i<SIZE; i++)
    printf("%.1lf ",m[i]);
printf("\n");
k = 1;
//========================
do {
    min = 0;
    max = k-1;
    do
    {
        c = (min+max)/2;
        if (m[c]>m[k]) 
        {
            min=c;
        }
        else {
            max=c; 
        }
        c = (min+max)/2; 
    }
    while(min != c);
    pos = min; 
    if(m[pos]<m[k])
    {
            pos++;
    }
    tmp = m[k]; 
    l=k;
    while (l>pos) {
        m[l]=m[l-1];
        l--;
    }
    m[pos]=tmp;
    k++;
} while (k != SIZE);
for (i=0; i<SIZE; i++)
    printf("%.1lf ",m[i]);
//========================
return 0;

}

有人可以帮忙,为什么排序不起作用?正如我所想,代码是正确的。也许我对算法不满意?

我正在尝试使用二进制插入排序。或者有人可以提供 C 代码替代方案(看看什么是不正确的)?

4

2 回答 2

0

的抽象算法insertion sort是:

function insertionSort(array A)
    for i from 1 to length[A]-1 do
        value := A[i] 
        j := i-1
        while j >= 0 and A[j] > value do
            A[j+1] := A[j]
            j := j-1
        done
        A[j+1] = value
    done

在 中实施C,我们有:

    void binaryInsertionSort (int a[], int n)
   {
     register int i, m;
     int hi, lo, tmp;

     for (i = 1; i < n; i++) {
        lo = 0, hi = i;
        m = i / 2;

        do {
            if (a[i] > a[m]) {
                lo = m + 1;
            } else if (a[i] < a[m]) {
                hi = m;
            } else
                break;

            m = lo + ((hi - lo) / 2);
        } while (lo < hi);

        if (m < i) {
            tmp = a[i];
            memmove (a + m + 1, a + m, sizeof (int) * (i - m));
            a[m] = tmp;
        }
    }
}
于 2012-07-09T17:27:33.730 回答
0

尝试这个:

void binaryInsertionSort (int *array, size_t size) {
register int i, middle;
int high, low, tmp;
static int comparisonCount = 0, swapCount = 0;
i = 1;
while (i < size) {
  low = 0, high = i;
  middle = i / 2;

  do {
    if (array[i] > array[middle]) {
      low = middle + 1;
    } else if (array[i] < array[middle]) {
      high = middle;
    } else
      break;

    middle = low + ((high - low) / 2);
  } while (low < high);

  comparisonCount++;
  if (middle < i) {
    tmp = array[i];
    memmove (array + middle + 1, array + middle, sizeof (int) * (i - middle));
    swapCount++;
    array[middle] = tmp;
  }
  i++;
}
printf("Comparison:%d Swap: %d\n", comparisonCount, swapCount);
}
于 2013-09-10T13:18:06.330 回答