Advertisement
earlution

BubbleSort

Nov 6th, 2023 (edited)
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.26 KB | None | 0 0
  1. // Optimised C# implementation of Bubble sort
  2. using System;
  3.  
  4. class GFG {
  5.     // An optimized version of Bubble Sort
  6.     static void bubbleSort(int[] arr, int n)
  7.     {
  8.         int i, j, temp;
  9.         bool swapped;
  10.         for (i = 0; i < n - 1; i++) {
  11.             swapped = false;
  12.             for (j = 0; j < n - i - 1; j++) {
  13.                 if (arr[j] > arr[j + 1]) {
  14.                      
  15.                     // Swap arr[j] and arr[j+1]
  16.                     temp = arr[j];
  17.                     arr[j] = arr[j + 1];
  18.                     arr[j + 1] = temp;
  19.                     swapped = true;
  20.                 }
  21.             }
  22.  
  23.             // If no two elements were
  24.             // swapped by inner loop, then break
  25.             if (swapped == false)
  26.                 break;
  27.         }
  28.     }
  29.  
  30.     // Function to print an array
  31.     static void printArray(int[] arr, int size)
  32.     {
  33.         int i;
  34.         for (i = 0; i < size; i++)
  35.             Console.Write(arr[i] + " ");
  36.         Console.WriteLine();
  37.     }
  38.  
  39.     // Driver method
  40.     public static void Main()
  41.     {
  42.         int[] arr = { 64, 34, 25, 12, 22, 11, 90 };
  43.         int n = arr.Length;
  44.         bubbleSort(arr, n);
  45.         Console.WriteLine("Sorted array:");
  46.         printArray(arr, n);
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement