forked from codinasion-archive/codinasion-monorepo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Written the code for largest two elements in an array in R language. c…
- Loading branch information
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
27 changes: 27 additions & 0 deletions
27
program/program/move-all-zeroes-to-end-of-array/move_all_zeroes_to_end_of_array.r
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
moveZeroesToEnd <- function(arr) { | ||
nonZeroIndex <- 1 | ||
|
||
for (i in 1:length(arr)) { | ||
if (arr[i] != 0) { | ||
arr[nonZeroIndex] <- arr[i] | ||
nonZeroIndex <- nonZeroIndex + 1 | ||
} | ||
} | ||
|
||
for (i in nonZeroIndex:length(arr)) { | ||
arr[i] <- 0 | ||
} | ||
|
||
return(arr) | ||
} | ||
|
||
|
||
arr1 <- c(1, 2, 0, 4, 3, 0, 5, 0) | ||
result1 <- moveZeroesToEnd(arr1) | ||
cat("Input : arr[] =", arr1, "\n") | ||
cat("Output : arr[] =", result1, "\n") | ||
|
||
arr2 <- c(1, 2, 0, 0, 0, 3, 6) | ||
result2 <- moveZeroesToEnd(arr2) | ||
cat("Input : arr[] =", arr2, "\n") | ||
cat("Output : arr[] =", result2, "\n") |