Created
December 11, 2013 07:37
-
-
Save Wind4/7906399 to your computer and use it in GitHub Desktop.
泛型冒泡排序
This file contains 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; | |
namespace Study | |
{ | |
public class Alogrithm | |
{ | |
/// <summary> | |
/// 交换数组中2个元素的位置 | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="source"></param> | |
/// <param name="i"></param> | |
/// <param name="j"></param> | |
static void SwapItem<T>(IList<T> source, int i, int j) | |
{ | |
T tmp = source[i]; | |
source[i] = source[j]; | |
source[j] = tmp; | |
} | |
/// <summary> | |
/// 冒泡排序算法 | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="source"></param> | |
static void BubbleSort<T>(IList<T> source) where T : IComparable<T> | |
{ | |
if (source == null) throw new ArgumentNullException("source"); | |
for (int i = 0; i < source.Count; i++) | |
for (int j = 0; j < source.Count; j++) | |
if (source[i].CompareTo(source[j]) < 0) | |
SwapItem(source, i, j); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment