简体   繁体   中英

why sorting alogrithim is going to infinite loop

My code: (i expect it sort passed array into ascending order).

void sort( int arr[], int n) {
    int c=0;

    for(int i = 0; i<n-1; ++i) {
        if (arr[i]>arr[i+1]) {
            c=arr[i];
            arr[i]=arr[i+1];
            arr[i]=c;
            i=0;
        }
    }

}   

example array: int arr[4]={3,1,2,4};

sort(arr,4);

Error: Infinite loop???

Your code for swapping two consecutive elements in the array is wrong. Replace the first three lines inside the if statement with:

c = arr[i];
arr[i] = arr[i+1];
arr[i+1] = c;

The last line is the one I fixed.

This algorithm is called a bubble sort .

EDIT: Another thing you need to do to ensure correct sorting is to set i to -1 instead of 0 at the end of the if statement. If you just set it to 0, then on the next iteration of the loop it will get incremented and become 1, which means that your code will not consider swapping the first two elements of the loop. (Thanks to the comment from Anton Savin.)

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