Implementing Bubble Sort
Implementing Bubble Sort In C#
using System; class BubbleSortExample { static void Main(string[] args) { int[] arr = { 64, 34, 25, 12, 22, 11, 90 }; Console.WriteLine("Original array:"); foreach (int i in arr) { Console.Write(i + " "); } Console.WriteLine(); BubbleSort(arr); Console.WriteLine("\nSorted array:"); foreach (int i in arr) { Console.Write(i + " "); } Console.ReadKey(); } static void BubbleSort(int[] arr) { int n = arr.Length; for (int i = 0; i < n - 1; i++) for (int j = 0; j < n - i - 1; j++) if (arr[j] > arr[j + 1]) { // Swap temp and arr[i] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } }
Step-by-Step Explanation
Let's break down the sorting process using the array { 64, 34, 25, 12, 22, 11, 90 }
:
- Initial Array:
[64, 34, 25, 12, 22, 11, 90]
- First Pass:Compare 64 and 34. Since 64 > 34, swap them:
[34, 64, 25, 12, 22, 11, 90]
- Compare 64 and 25. Swap:
[34, 25, 64, 12, 22, 11, 90]
- Continue this process for the rest of the array, "bubbling" the largest number to the end.
- After the first pass, the array becomes
[34, 25, 12, 22, 11, 64, 90]
- Subsequent Passes:Repeat the process, ignoring the last elements each time since they are already sorted.
- Second pass:
[25, 12, 22, 11, 34, 64, 90]
- Continue until the entire array is sorted.
- First Pass:Compare 64 and 34. Since 64 > 34, swap them:
- Final Sorted Array: After all passes, the array will be sorted:
[11, 12, 22, 25, 34, 64, 90]
Expected Results
- Before Sorting: The original array is displayed.
- After Sorting: The sorted array is displayed in ascending order.
Source Code:
Download
17 comments