Sorting an Array in Ruby without using Sort method

后端 未结 7 1918
感动是毒
感动是毒 2020-12-20 02:20

I\'m trying to use the bubble sort method to sort an array of only three numbers. The code I\'m using is below.

def my_sort(list)
  return list if list.         


        
相关标签:
7条回答
  • 2020-12-20 02:26
    #Using bubble sort algorithm in ruby
    
    a = [1,5,7,2,3,50,78,34,89]
    
    a.size.times.each do |t|
     i=0
     a.each do |b|
       if b > a[i+1]
         a[i],a[i+1] = a[i+1],a[i]
       end
       i+=1 if i < a.size-2
     end
    end
    print a
    #output: [1, 2, 3, 5, 7, 34, 50, 78, 89]
    
    0 讨论(0)
  • 2020-12-20 02:32
    def sort(arr)
        arr_len = arr.length - 1
        swap = true
        while swap
            swap = false
            arr_len.times do |i|
             if arr[i] > arr[i+1]
               arr[i],arr[i + 1] = arr[i + 1],arr[i]
               swap = true
             end
            end
         end
         p arr
    
    end
    
    0 讨论(0)
  • 2020-12-20 02:37

    You're missing an end after swapped = true. It would be best to indent your code thoroughly and accurately to avoid this kind of problem:

    def my_sort(list)
      return list if list.size <= 1 
    
      swapped = false
      while !swapped
        swapped = false
        0.upto(list.size-2) do |i|
          if list[i] > list[i+1]
            list[i], list[i+1] = list[i+1], list[i]
            swapped = true
          end
        end
      end
    
      list
    end
    
    0 讨论(0)
  • 2020-12-20 02:40

    Your code works for that specific array. Because your loop is looking if the next element is higher, then swipe. But what about more elements in the array? This is recursive solution for all cases.

    def my_sort(list, new_array = nil)
    
      return new_array if list.size <= 0
      if new_array == nil
        new_array = []
      end
      min = list.min
      new_array << min
      list.delete(min)
    
      my_sort(list, new_array)
    
    end
    
    puts my_sort([3, 1, 2, 20, 11, 14, 3, 6, 8, 5])
    
    0 讨论(0)
  • 2020-12-20 02:46

    You're missing an end

      if list[i] > list[i+1]
        list[i], list[i+1] = list[i+1], list[i]
        swapped = true
      end # <--------------------------------------------------------
    

    Edit: As the other answer mentions, indent your code to make these errors more visible.

    0 讨论(0)
  • 2020-12-20 02:52

    This looks a better and quicker one.

    arr = [1,5,7,2,3,50,78,34, 1, 15, 89, 8]
    
    def sort_array(arr)
      arr.size.times do
        arr.map.with_index do |num, index|
          next if index.eql?(arr.size - 1)
          arr[index], arr[index+1] = arr[index+1], arr[index] if num > arr[index+1]
        end
      end
    end
    

    Call the above method as print sort_array(arr) to get expected result.

    0 讨论(0)
提交回复
热议问题