# R Program to sort a vector in ascending and descending order

February 8, 2023, Learn eTutorial
2067

## How to sort a vector in ascending and descending order?

To sort a Vector in R programming, we are using a sort() function. The sort() function is an R built-in function that can able to arrange the vectors in both ascending and descending order. by default the sort() function will arrange in ascending order, if we need it in descending order we have set decreasing=TRUE. The syntax is like

`sort(x, decreasing, na.last) `

• x is the vector to be sorted,
• decreasing is the Boolean value to sort in descending order, and
• na.last is the Boolean value to put NA at the end.

## How to implement a vector sorting algorithm in an R program?

In this R program, we directly give the values to the built-in function sort(). For that first, we have to add the vector values into 'A'. Call the sort() function twice to arrange the vectors in ascending order, and in descending order by setting decreasing=TRUE in the second function call. Finally, print the result.

## ALGORITHM

STEP 1: Assign variable A with vector values

STEP 2: display the original values of the vector first

STEP 3: Call the sort() for getting results in ascending order

STEP 4: Print the result

STEP 5: Call sort() function again by setting decreasing=TRUE

STEP 6: Print the result of the function

## R Source Code

```                                          ```A= c(10, 12, 30, 25, 8, 29)
print("Original Vectors:")
print(A)
print("Sort in ascending order:")
print(sort(A))
print("Sort in descending order:")
print(sort(A, decreasing=TRUE))
```
```

## OUTPUT

```[1] "Original Vectors:"
[1] 10, 12, 30, 25, 8, 29
[1] "Sort in ascending order:"
[1]  8 10 12 25 29 30
[1] "Sort in descending order:"
[1] 30 29 25 12 10  8
```

VIEW ALL
VIEW ALL