R Program to sort a vector in ascending and descending order

How to sort a vector in ascending and descending order

Here we are explaining how to write an R program to sort a Vector in ascending and descending order. Here we are using a built-in function sort() for this finding. The sort() function helps to sort a vector by its values. The sorting can be possible in both ascending and descending order. By default, it sorts in ascending order for making sorting in ascending order need to set decreasing=TRUE. The syntax of sorting is like

sort(x, decreasing, na.last) 
 

Here 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 sort a Vector in ascending and descending order in the R program

Below are the steps used in the R program to get the last value in a given vector. In this R program, we directly give the values to built-in functions. For that first, we find the length of the vector into variable A. Finally, call the sort function by setting decreasing=TRUE for making it descending order.

ALGORITHM

STEP 1: Assign variable A with vector values

STEP 2: First print original vector values

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

STEP 4: After sort by setting decreasing=TRUE

STEP 5: 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