Last active
August 29, 2015 14:05
-
-
Save KentaYamada/0d01a6a68eff948c8358 to your computer and use it in GitHub Desktop.
バブルソート
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
class BubbleSort | |
{ | |
static void Main() | |
{ | |
var array = new List<int>(); | |
var rand = new Random(); | |
for (int i = 0; i < 10000; i++) | |
{ | |
//10000個の整数をランダムで生成 | |
array.Add(rand.Next(10000)); | |
} | |
var sw = new StopWatch(); | |
sw.Reset(); | |
sw.Start(); | |
//計測時はどっちかコメントアウトして計測して下さい | |
pattern_1(array.ToArray()); | |
pattern_2(array.ToArray()); | |
sw.Stop(); | |
Console.WriteLine(sw.Elapsed); | |
//処理結果(My PC) | |
//パターン1:6秒台 | |
//パターン2:3秒台 | |
} | |
private static void Pattern_1(int[] array) | |
{ | |
//一般的なバブルソート | |
for (int i = 0; i < (array.Length - 1); i++) | |
{ | |
for (int j = 0; j < array.Length - 1; j++) | |
{ | |
if (array[j] > array[j + 1]) | |
{ | |
var tmp = array[j + 1]; | |
array[j + 1] = array[j]; | |
array[j] = tmp; | |
} | |
} | |
} | |
} | |
private static void Pattern_2(int[] array) | |
{ | |
//1回目のループは何番目の要素までの並び替えを行っているか知ることができる。 | |
//パターン1だと、並び替えが終わった要素も再び条件判断に含まれているので、 | |
//並び替えが必要な要素から検索を始めることで処理時間を短縮することができる。 | |
for (int i = 0; i < (array.Length - 1); i++) | |
{ | |
for (int j = 0; j < (array.Length) - 1; j++) | |
{ | |
if (array[i] > array[j + 1]) | |
{ | |
var tmp = array[j + 1]; | |
array[j + 1] = array[i]; | |
array[i] = tmp; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment