Dissecting the First C# Program You Created - 03
Enjoy!
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] + " "); }}
static void Main(string[] args){
int[] array = { 3, 2, 1, 4, 8 };
Console.Write("Before sort: ");
PrintArray(array);
Console.WriteLine();
SelectionSort(array);
Console.Write("After sort : ");
PrintArray(array);
Console.WriteLine();
Console.ReadLine();}
private static void SelectionSort(int[] sortArray)
{
int smallest = 0;
int smallestIndex = 0;
/* advance the position through the entire array */
/* (could do i < n-1 because single element is also min element) */
for (int i = 0; i < sortArray.Length; i++)
{
smallest = sortArray[i];//the smallest value is at index 0
smallestIndex = i;//store the index of the smallest value
//find the index of the smallest value
for (int x = i + 1; x < sortArray.Length; x++)
{
if (sortArray[x] < sortArray[i])
smallestIndex = x;
}
//swap/exchange the smallest value found with last index
sortArray[i] = sortArray[smallestIndex];
sortArray[smallestIndex] = smallest;
}
}
private static void PrintArray(int[] array){ for (int i = 0; i < array.Length; i++) { Console.Write(array[i] + " "); }}