Bubble Sort Algorithm in C

后端 未结 4 594
醉梦人生
醉梦人生 2020-12-22 13:31

The program I\"m trying to finish is a program using the bubble sort algorithm. I am not sure what is the problem or in which function the problem is in. The problem is th

4条回答
  •  暖寄归人
    2020-12-22 14:15

    All I follow from the above examples is an implementation of the exchange sort.

    The exchange sort on the outer loop checks each entry in the table against the first element, exchanging when necessary. At then end of the inner loop, the lowest element is in position 1, then it begins with position 2, comparing it to the remaining elements, and doing an exchange. Even if the array was already in order, the sort cannot stop. It has to do a n*(n-1) compares. An array of 50 elements, already sorted will do 50*49 comparisons.

    The bubble sort works differently

    set a swap flag to zero. Then slide along the array, comparing position(i) to position(i+1). If a swap takes place, you do the sort again.

    here is some pseudo code.

    1. swap = 0
    2. do {
    3. for (i=o;i< no-elements-1;i++) {
    4. if (array[i] > array[i+1])
    5. {
    6. do the exchange
    7. set swap=1
    8. }
    9. /**/
    10. } while (swap == 1);

    The above illustrates the bubble sort.

    Note. if the data is in order, there is no swap and there is no second loop. The sort algorithm is able to quit early.

    if a fifty element array is in order, the sort would have done 50 comparisons and would have stopped. The exchange sort, which is described earlier would have to do 50*49 or 2450 comparisons.

提交回复
热议问题