Implementing a sort using insertion sort algorithm.
1. Create a new console project.
2. Edit the Program.cs inside static void Main(string[] args) file as shown below.
static void Main(string[] args){ int[] array = { 2, 3, 1, 9, 4, 7, 5, 8, 6, 10, 20, 12, 18, 11, 15, 16 }; Console.Write("Before sort: "); PrintArray(array); Console.WriteLine(); BubbleSort(array); Console.Write("After sort: "); PrintArray(array); Console.ReadLine();}
private static void BubbleSort(int[] array){ int temp; for (int i = array.Length; i >= 0 ; i--) { for (int x = 0; x < array.Length - 1; x++) { if (array[x] > array[x + 1]) { temp = array[x]; array[x] = array[x + 1]; array[x + 1] = temp; } } }}
private static void PrintArray(int[] array){ for (int i = 0; i < array.Length; i++) { Console.Write(array[i] + " "); }}
3. Press F5 to run and see the results.
4. Enjoy!
References:
http://www.sorting-algorithms.com/bubble-sort
http://en.wikipedia.org/wiki/Bubble_sort
http://www.algolist.net/Algorithms/Sorting/Bubble_sort

No comments:
Post a Comment