简体   繁体   中英

cs50 pset3 - Sorting

void sort(int values[], int n)
{
    int swap, i;
    do{
    swap = 0;
    for(i=0; i<n; i++){
        if(values[i]>values[i+1]){
            int temp = values[i+1];
            values[i+1] = values[i];
            values[i+1]=temp;
            swap = 1;
            }printf("%d\n", values[i]);
        }
    }while(swap == 1);
}

it doesn't seem to be working. what could be wrong?

values: 59797 10425 37569 52527 36285

as sorted: 10425 37569 52527 36285 59797

CHANGED IT

void sort(int values[], int n)
{
    int swap, i, temp;
    // TODO: implement an O(n^2) sorting algorithm
    do{
    swap = 0;
    for(i=0; i<n; i++){
        if(values[i]>values[i+1]){
            temp = values[i+1];
            values[i+1] = values[i];
            values[i]=temp;
            swap = 1;
            }
            printf("%d\n", values[i]);
        }
    }while(swap == 1);
}

values: 59797 10425 37569 52527 36285

as sorted: 0 10425 36285 37569 52527

Look at these two lines.

 values[i+1] = values[i];
 values[i+1]=temp;

Does it not look like you're setting the same element twice, to two different values, for no effect?

What purpose does the first statement serve? There is your answer.


When i is its last value ( n-1 ), then you will compare values[n-1] with values[n] .
One of those elements is not in your array .
You just did an out-of-bounds access.

I suggest you consider using built in function. qsort may simplify things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM