Write a program to merge two sorted vectors into a single sorted vector.
Do not use the sort(x) function, and try to make your program as efficient
as possible. That is, try to minimise the number of operations required to
merge the vectors.
能否一起探讨一下有效的算法,我先抛砖引玉,思想来自网络的帖子:
- a <- -10:10
- b <- 2:8
- checkSort <- function(x) {
- result = TRUE
- for (i in 1:(length(x) - 1)) {
- for (j in (i + 1):length(x)) {
- if (x[j - 1] > x[j]){
- result <- FALSE
- break
- }
- }
- }
- return(result)
- }
- mergesort <- function(a, b) {
- if (checkSort(a) & checkSort(b)){
- a.length <- length(a)
- b.length <- length(b)
- n <- a.length + b.length
- result.vec <- rep(0, n)
- i <- 1
- j <- 1
- k <- 1
- while(i <= a.length & j <= b.length){
- if(a[i] <= b[j]) {
- result.vec[k] <- a[i]
- i <- i +1
- k <- k + 1
- } else {
- result.vec[k] <- b[j]
- j <- j + 1
- k <- k + 1
- }
- }
- while(i <= a.length) {
- result.vec[k] <- a[i]
- i <- i +1
- k <- k + 1
- }
- while(j <= b.length) {
- result.vec[k] <- b[j]
- j <- j + 1
- k <- k + 1
- }
- return(result.vec)
- } else {
- cat("please input two sorted vectors")
- }
- }
- mergesort(a, b)


雷达卡






京公网安备 11010802022788号







