4

我遇到问题,此代码中的最后一个数字未排序。

   // This is the more advanced optimzed version of bubble sort
        int modifiedBubbleSortArray(int array[])
        {

        int swapped = 0;

         do {
            swapped = false;
            // We specify a loop here for the sorting
            for(int i=0;i<NUM_ARRAYS;i++)
            {
                // We specify aother loop here for the sorting
                for(int j=0;j< i - 1 /* <<< here we make less comparisns on each pass each time */ ;j++)
                {
                    // If the array i is better than j we enter this swap
                    if (array[j]<array[j+1])  
                    {
                        // We swap here for the functions
                        swap(array[j], array[j+1]);
                        // We measure the amount of times we swap
                        amountOfSwaps += 1;
                        // If we swapped we break out of the loop
                        swapped = true;
                    }
                }
            }
             } while (swapped);
        printArray(array);
        return amountOfSwaps;

        }

        // Here we swap values to sort them
        void swap(int & value1, int & value2)
        {
            // We specify a temp and use it to swap
            int temp=value1; 
            value1=value2;
            value2=temp;

        }
4

2 回答 2

2

内循环应该是:

if (array[j]>array[j+1]) 
{ 
  // We swap here for the functions 
  swap(array[j], array[j+1]); 
  // We measure the amount of times we swap 
  amountOfSwaps += 1; 
} 

试一试,看看您的冒泡排序变体是否正确排序。

要按降序排序,只需更改 if 条件:

if (array[j]<array[j+1]) 

另一个错误是内部 for 循环。将其更改为:

for(int j=0;j<=i-1;++j)

更新(基于添加了交换测试的最后更改):

bool swapped = false; 

// We specify a loop here for the sorting 
for(int i=0;i<NUM_ARRAYS;i++) 
{ 
    // We specify aother loop here for the sorting 
    for(int j=0;j<=i-1;++j)
    { 
        // If the array i is better than j we enter this swap 
        if (array[j]<array[j+1])   
        { 
            // We swap here for the functions 
            swap(array[j], array[j+1]); 
            // We measure the amount of times we swap 
            amountOfSwaps += 1; 
            // If we swapped we break out of the loop 
            swapped = true; 
        } 
    } 
    // If no swaps this iteration, break out
    if (!swapped)
        break;
} 

如果您真的想要一个好的排序,请查看自省排序- 快速排序的一种变体。该算法更复杂,但排序也更高效,为 O(N log N) 而不是冒泡排序的复杂度 O(N^2)。

于 2011-10-27T02:35:44.457 回答
0

亲爱的朋友(神秘主义者)

下面的代码是用 java 编写的,但这是完美的,例如。冒泡排序算法。

    int[] nums = { 12 , 5 , 16 , 9 , 25 , 3 , 45 , 11 , 14 };
    int temp;

    for(int y = 1 ; y < nums.length - 1 ; y++) {

        for(int x = 0 ; x < nums.length - y ; x++) {

            if(nums[x] > nums[x+1]) {

                temp = nums[x];
                nums[x] = nums[x+1];
                nums[x+1] = temp;

            }
        }
    }
于 2018-08-02T14:02:15.057 回答