Saturday, 15 January 2011

ruby - Compare two consecutive elements in an array -


I want to create a "bubble sort" method, which means that I take two elements in an array consistently, their Compare and if the left element is more than the right element, then they should change the situation. Unless my array is sorted in ascending order, I want to repeat it.

My code works only partly if my array is too big then nothing will happen (I have to leave Ruby with CTRL + C) with my array my code works fine with 5 elements Is:

  def bubbles (array) while array.each_cons (2) .any? {| A, B (A & lt; = & gt; b) & gt; = "}" If there are two consecutive elements where the first one is # bigger than the other. I know that the error should be in any way. Do Array.each_with_index.map | Number, index | If array [index + 1]. Nil? Number break elithief number & gt; Array [index + 1] array [index], array [index + 1] = array [index + 1], array [index] # swap position! If I call my method with an array of 4 elements, then it works fine:  
  Bubbles ([1, 5, 8, 3]) # => [1, 3, 5, 8]  

If I say it with a large array, it does not work:

  Bubbles ([5 , 12, 2, 512, 99, 1, 2, 323, 2, 12]) # = & gt; nothing happen. I have to rub Ruby with ctrl + c  

Have I somehow made an infinite loop with the statement of my time?

"post-text" itemprop = "text">

The problem is in your stop condition unless you have an array, as far as each element is less is less than the next but in your long array you have duplicated the elements, so the sorted elements will have adjacent elements which are identical of each other.

If your code is not very fancy then your life is easy :)

  while array.each_cons (2) .What? {| A, B One & gt; B}  

No comments:

Post a Comment