Exclusive Clothing Sale On Soft & Soothe

Get up to 63% off on our latest collection.

Shop Now

Sort an array in descending order

 

Sort an array in descending order


In this article, we will see how to sort an array in descending order using various logics.

1. Using in-build method | Using Array.Sort() and Array.Reverse() Method


1 public static void SortArray()
2
3 {
4
5
6
7 int[] arr = new int[] { 1, 4, 2, 9, 5, 6,3,11 };
8
9
10
11 // Sort array in ascending order.
12
13 Array.Sort(arr);
14
15
16
17 // reverse array
18
19 Array.Reverse(arr);
20
21
22
23 foreach (int value in arr)
24
25 {
26
27 Console.Write(value + " ");
28
29 }
30
31
32
33 }
C#
output

2. Sort an array in ascending order without using inbuilt C# function


1public static void SortArray()
2
3 {
4
5
6
7 int[] arr = new int[] { 1, 4, 2, 9, 5, 6,3,11 };
8
9
10
11 int temp = 0;
12
13
14
15 for (int i = 0; i <= arr.Length - 1; i++)
16
17 {
18
19 for (int j = i + 1; j < arr.Length; j++)
20
21 {
22
23 if (arr[i] > arr[j])
24
25 {
26
27 temp = arr[i];
28
29 arr[i] = arr[j];
30
31 arr[j] = temp;
32
33 }
34
35 }
36
37 }
38
39 Console.WriteLine("Array sort in asscending order");
40
41 foreach (var item in arr)
42
43 {
44
45 Console.WriteLine(item);
46
47 }
48
49 Console.ReadLine();
50
51
52
53 }
C#



Output



3. Sort an array in descending order without using the inbuilt C# function.


1public static void SortArray()
2
3 {
4
5
6
7 int[] arr = new int[] { 1, 4, 2, 9, 5, 6,3,11 };
8
9
10
11 int temp = 0;
12
13
14
15 for (int i = 0; i <= arr.Length - 1; i++)
16
17 {
18
19 for (int j = i + 1; j < arr.Length; j++)
20
21 {
22
23 if (arr[i] < arr[j])
24
25 {
26
27 temp = arr[i];
28
29 arr[i] = arr[j];
30
31 arr[j] = temp;
32
33 }
34
35 }
36
37 }
38
39 Console.WriteLine("Array sort in descending order");
40
41 foreach (var item in arr)
42
43 {
44
45 Console.WriteLine(item);
46
47 }
48
49 Console.ReadLine();
50
51
52
53 }
C#


Output



Share this

Related Posts

Previous
Next Post »

Exclusive Clothing Sale On Soft & Soothe

Get up to 63% off on our latest collection.

Shop Now