对两个已排序数组的元素进行排序,而不使用.sort方法,并将已排序的元素放入RUBY中的新数组中
我有两个数组,如下:
a = [1,4,6,9]
b = [2,5,7,8]
我的输出应该是:
c = [1,2,4,5,6,7,8,9]
我该怎么做?
答案 0 :(得分:0)
你总是希望利用要合并的两个数组已经排序的事实。这是一种方法:
a
第一行是避免变异(更改)b
或> dput(daata)
structure(list(P1 = structure(c(1L, 1L, 3L, 3L, 5L, 5L, 5L, 5L,
4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 2L, 2L), .Label = c("Apple",
"Grape", "Orange", "Peach", "Tomato"), class = "factor"), P2 = structure(c(4L,
4L, 3L, 3L, 5L, 5L, 5L, 5L, 6L, 6L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 6L, 6L), .Label = c("Banana", "Cucumber", "Lemon", "Orange",
"Potato", "Tomato"), class = "factor"), P1_location_subacon = structure(c(NA,
NA, 1L, 1L, 1L, 1L, 1L, 1L, NA, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), .Label = c("Fridge", "Table"), class = "factor"),
P1_location_all_predictors = structure(c(2L, 2L, 3L, 3L,
3L, 3L, 3L, 3L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L), .Label = c("Table,Desk,Bag,Fridge,Bed,Shelf,Chair",
"Table,Shelf,Cupboard,Bed,Fridge", "Table,Shelf,Fridge"), class = "factor"),
P2_location_subacon = structure(c(1L, 1L, 1L, 1L, NA, NA,
NA, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Fridge",
"Shelf"), class = "factor"), P2_location_all_predictors = structure(c(3L,
3L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 2L, 2L, 2L, 2L, 3L, 3L,
3L, 3L, 3L, 3L), .Label = c("Shelf,Fridge", "Shelf,Fridge,Bed",
"Table,Shelf,Fridge"), class = "factor")), .Names = c("P1",
"P2", "P1_location_subacon", "P1_location_all_predictors", "P2_location_subacon",
"P2_location_all_predictors"), row.names = c(NA, -20L), class = "data.frame")
。
答案 1 :(得分:0)
这是一个可以帮助你做你想要的功能。
def my_sort_function(a,b)
n = a.length + b.length
if a.length < b.length
min = a.length
else
min = b.length
end
c=[]
min.times do |i|
if a[i] > b[i]
c << b[i]
c << a[i]
else
c << a[i]
c << b[i]
end
end
if min == a.length
(c << b[(min)..(b.length-1)]).flatten!
else
(c << a[(min)..(a.length-1)]).flatten!
end
loop do
swapped = false
(n-1).times do |i|
if c[i] > c[i+1]
c[i], c[i+1] = c[i+1], c[i]
swapped = true
end
end
break if not swapped
end
c
end
a = [1,4,6]
b = [2,5,7,8]
puts a #=> a:[1,4,6]
puts b #=> b:[2,5,7,8]
c= my_sort_function(a,b)
puts c #=> c:[1,2,4,5,6,7,8]
puts "sorting Done!"