ruby Ruby的算法和数据结构 - #4 Merge Sort

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby Ruby的算法和数据结构 - #4 Merge Sort相关的知识,希望对你有一定的参考价值。

def mergeArrays(arr,start_1,end_1,start_2,end_2)

    temp = Array.new(end_1 + end_2 - start_1 - start_2 + 2)
    index_1 = start_1  # Marks the index in the first sub-array, which needs to be put into the temporary array next
    index_2 = start_2  # Marks the index in the second sub-array, which needs to be put into the temporary array next
    index = 0        # Mark the index in the Temporary array which is being filled
     

    while ( index_1 <= end_1 ) || ( index_2 <= end_2 )
        
        if ( index_1 <= end_1 ) && ( index_2 <= end_2 ) && (arr[index_1] < arr[index_2] ) 
            temp[index] = arr[index_1]
            index += 1
            index_1 += 1
        elsif ( index_2 <= end_2 )
            temp[index] = arr[index_2]
            index += 1
            index_2 += 1
        else
            temp[index] = arr[index_1]
            index += 1
            index_1 += 1
        end
    end
    
    
    (0..(index-1)).each{ |x|
        arr[x + start_1] = temp[x]
    }
    
end

def mergeSort(arr,startIndex,endIndex)
    return if endIndex <= startIndex
    length = endIndex - startIndex + 1
    mergeSort(arr,startIndex,startIndex + length/2 -1)
    mergeSort(arr,startIndex + length/2 , endIndex)
    mergeArrays(arr,startIndex,startIndex + length/2 -1,startIndex + length/2 , endIndex)
end


original_array=[2,19,5,4,3,14,2]
puts "Sorted Array Using Merge Sort:"
mergeSort(original_array,0,original_array.length - 1)
p original_array


##Output:
## Sorted Array Using Merge Sort:
## [2, 2, 3, 4, 5, 14, 19]

#Example 2

def merge_sort(lst)
  return lst if lst.length <= 1
  mid = lst.length / 2
  left = merge_sort(lst[0..mid - 1])
  right = merge_sort(lst[mid..lst.length])
  merge(left, right)
end

def merge(left, right)  
  result = []; i = j = 0;
  while i < left.size and j < right.size
    if left[i] <= right[j]
      result << left[i]; i+=1;
    else
      result << right[j]; j+=1;
    end
  end
  while i<left.size do 
    result << left[i]; i+=1;
  end
  while j<right.size
    result << right[j]; j+=1;
  end
  result
end

#test
p merge_sort [4,3,6,1,2,7,8,5,9,0] #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

以上是关于ruby Ruby的算法和数据结构 - #4 Merge Sort的主要内容,如果未能解决你的问题,请参考以下文章

3-4 8精彩算法集合。struct(C,ruby)

ruby Ruby的算法和数据结构 - #6队列

ruby Ruby的算法和数据结构 - #8二叉树

ruby Ruby的算法和数据结构 - #7 LinkedList

ruby Ruby的算法和数据结构 - #5 Stack

ruby Ruby的算法和数据结构 - #3快速排序