加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 冒泡排序不会使用此算法对最后一个数字进行排序

发布时间:2020-12-16 07:27:33 所属栏目:百科 来源:网络整理
导读:我遇到问题,此代码中的最后一个数字未被排序. // 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
我遇到问题,此代码中的最后一个数字未被排序.

// 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;

        }

解决方法

内循环应该是:

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])

另一个bug是内部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;
}

如果你真的想要一个好的排序,请查看introspection sort – 快速排序的变体.该算法更复杂,但排序也更有效,是O(N log N)而不是O(N ^ 2),这是冒泡排序的复杂性.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读