Search code examples
cbubble-sortsorting

Bubble sort all but first spot


If I change the condition (i < n -1) to (i < n) it glitches, and as it is now, all but the first position [0] gets sorted.

int sortIndexByDate(Match match[], int n)
{
    int i, j, sum[n], swapped;
    for (i = 0; i < n; i++)
        sum[i] = match[i].d.year*10000 + match[i].d.month*100 + match[i].d.day;
    do {
        swapped = false;
        for (i = 1; i < n - 1; i++) {
            if (sum[i] < sum[i + 1]) {
                swapInt(&sum[i], &sum[i+1]);
                swapMatch(&match[i], &match[i+1]);
                swapped = true;
            }
        }
        n--;
    } while (swapped);
}

Solution

  • You are starting at i = 1 in inner loop. Hence sum[0] is being ignored.

    Change it to

    for (i = 0; i < n-1; i++) {