在冒泡排序中实现while循环?

时间:2013-01-24 13:39:40

标签: ruby while-loop

我想在Ruby中编写一个冒泡排序程序。如果没有先在我的代码中指出错误,请不要建议一种新的方法。我可以查找Ruby冒泡排序方法的答案,但我无法弄清楚为什么我的代码不起作用。

我正在使用while循环,但是,我的方法似乎不会连续循环,直到它完全传递一次而不进行交换。我没有正确使用while循环吗?

这是我的剧本:

def bubblesort(array)
      i = 0 
      swapped = true
      lenght = array.length-1
      while swapped do
          swapped = false
          while i <lenght
              n = i +1
              if array[i] > array[n]
              dummy = array[i]
              array[i]= array[n]
              array[n] = dummy  
              swapped = true

              end
             i+=1
          end

      end
      return array
end

4 个答案:

答案 0 :(得分:1)

问题是当您在i内进行第二次迭代时,0变量无法重置为while swapped do

这样做,第二个循环不会再输入一次。

这样可行:

def bubblesort(array)
      swapped = true
      lenght = array.length-1
      while swapped do
          i = 0
          swapped = false
          while i <lenght
              n = i +1
              if array[i] > array[n]
                  dummy = array[i]
                  array[i]= array[n]
                  array[n] = dummy  
                  swapped = true
              end
             i+=1
          end
      end
      return array
end

答案 1 :(得分:1)

这是11个元素。您可以将大小更改为任意数字

#include <iostream>
#include <conio.h>
using namespace std;

void swap(int *,int *);
void printArr(int *,int Siz=11);
int main(){

int a[]={1,4,15,10,12,6,3,2,8,5,7};
//int a[]={1,2,3,4,5,5,7,8,10,11,9};

int len=11,i=0,j=0,temp=0;
bool swapped=false;
    while(i<len){

        swapped=false;j=0;
        while(j<len-1){
            if(a[j]>a[j+1]){
                swap(&a[j],&a[j+1]);
                swapped=true;
            }
            cout<<"loop : "<<i<<" "<<a[j]<<" "<<a[j+1]<<endl;
            j+=1;

        }
        i+=1; len-=1; //as the largest value has already moved to last location. need no further comparison
        if(!swapped) break;
    }
    printArr(a);
    system("pause");
}

void swap(int *a,int *b){
    int t=*a;
    *a=*b;
    *b=t;

}

void printArr(int *a,int Siz){
    for(int i=0; i<Siz; i++) cout<<a[i]<<" "; 
}

答案 2 :(得分:0)

这将有效:

http://codepad.org/8BsoiWQo

def bubblesort(array)
      i = 0 
      swapped = true
      length = array.length
      while i < length-1 and swapped do # also check for end of array
          swapped = false
          n = i +1  # second loop variable 'n' should be initialized here
          while n < length
              if array[i] > array[n]
                  dummy = array[i]
                  array[i]= array[n]
                  array[n] = dummy  
                  swapped = true
              end
             n += 1 # 'n' should be incremented here...
          end
          i += 1 # and 'i' here
      end
      return array
end

我不是一个红宝石程序员,但是我尝试了相当于此代码的C#,它运行良好。

答案 3 :(得分:0)

史蒂文建议。问题是你的i = 0。它应该被移动到第一个while循环中,以便它可以重置。

避免与第二次循环的所有混乱。

(array.length-1).times do | i |
 码..... 端

以上作品很棒。每次重置i。

相关问题