ratio/csharp/bubble_sort.cs

60 lines
1.4 KiB
C#
Raw Normal View History

2017-03-11 23:43:13 -07:00
/*
* Copyright (C) 2017 Kevin Cotugno
* All rights reserved
*
* Distributed under the terms of the MIT software license. See the
* accompanying LICENSE file or http://www.opensource.org/licenses/MIT.
*/
using System;
class Ratio
{
public static void Main(string[] args)
{
int num;
int[] elements;
Console.Write("How many elements? ");
try {
num = int.Parse(Console.ReadLine());
elements = new int[num];
for (int i = 0; i < num; i++)
{
Console.Write("Enter element {0}: ", i + 1);
elements[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Unsorted: [{0}]", string.Join(", ", elements));
2017-03-12 09:42:14 -07:00
Console.WriteLine("Sorted: [{0}]", string.Join(", ", BubbleSort(elements)));
2017-03-11 23:43:13 -07:00
}
catch {
Environment.Exit(1);
}
}
private static int[] BubbleSort(int[] unsorted)
{
2017-03-12 09:42:14 -07:00
var count = unsorted.Length;
2017-03-11 23:43:13 -07:00
int t;
for (int i = 0; i < count; i++)
{
for (int j = 0; j < (count - i - 1); j++)
{
2017-03-12 09:42:14 -07:00
if (unsorted[j] > unsorted[j + 1])
2017-03-11 23:43:13 -07:00
{
2017-03-12 09:42:14 -07:00
t = unsorted[j];
unsorted[j] = unsorted[j + 1];
unsorted[j + 1] = t;
2017-03-11 23:43:13 -07:00
}
}
}
2017-03-12 09:42:14 -07:00
return unsorted;
2017-03-11 23:43:13 -07:00
}
}