Bubble Search
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
private static int[] array;
static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
// Write Your Code Here
array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = a[i];
}
bubbleSort();
}
private static void bubbleSort() {
int n = array.Length;
// Number of swaps for all array iterations
int totalSwaps = 0;
for (int i = 0; i < n; i++) {
// Track if a swap was made
bool swapped = false;
for (int j = 0; j < array.Length - 1; j++) {
if (array[j] > array[j + 1]) {
int tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
swapped = true;
totalSwaps++;
}
}
// Terminate loop as soon as array is sorted
if (!swapped) {
break;
}
}
// Print answer
Console.WriteLine("Array is sorted in "+ totalSwaps + " swaps." );
Console.WriteLine("First Element: " + array[0]);
Console.WriteLine("Last Element: " + array[n - 1]);
}
}
留言
張貼留言