Q:

C# program to sort an array in descending order using bubble sort

0

C# program to sort an array in descending order using bubble sort

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to implement bubble sort to arrange elements in the descending order is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to implement bubble to sort an array 
//in descending order.

using System;

class Sort
{
    static void BubbleSort(ref int []intArr)
    {
        int temp=0;
        
        int pass = 0;
        int loop = 0;

        for ( pass= 0; pass <= intArr.Length - 2; pass++)
        {
            for ( loop = 0; loop <= intArr.Length - 2; loop++)
            {
                if (intArr[loop] < intArr[loop + 1])
                {
                    temp = intArr[loop + 1];
                    intArr[loop + 1] = intArr[loop];
                    intArr[loop] = temp;
                }
            }
        }
    }
    static void Main(string[] args)
    {
        int[] intArry = new int[5] { 65,34,23,76,21 };

        Console.WriteLine("Array before sorting: ");
        for (int i = 0; i < intArry.Length; i++)
        {
            Console.Write(intArry[i]+" ");
        }
        Console.WriteLine();

        BubbleSort(ref intArry);
        
        Console.WriteLine("Array before sorting: ");
        for (int i = 0; i < intArry.Length; i++)
        {
            Console.Write(intArry[i] + " ");
        }
        Console.WriteLine();
    }
}

Output:

Array before sorting:
65 34 23 76 21
Array before sorting:
76 65 34 23 21
Press any key to continue . . .

Explanation:

In the above program, we created a class Sort that contains two static methods BubbleSort() and Main(). The BubbleSort() method is used to sort the elements of integer array in the descending order.

Here we used the "if" condition to check the current value is less than the next value in the array. If the current value is less than to the next value then we swapped the value using a temporary variable.

Now look to the Main() method, The Main() method is the entry point for the program. Here, we created the array of integers then sorted the array in descending order using the BubbleSort() method and print the sorted array on the console screen.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Data Structure Solved Programs/Examples

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to sort an array using quick sort... >>
<< C# program to sort an array in ascending order usi...