C#几种排序

 void Start()
 {
     List ints = new List() {5, 8, 7, 2, 1, 4, 6};
     
     BubbleSort(ints);
     //使用简单选择排序法
     //SimpleSort(ints);
     //使用快速排序法
     //QuickSort(ints, 0, ints.Count - 1);

     //输出
     foreach (int i in ints)
     {
         Debug.Log("排序后:" + i);
     }
 }

//冒泡排序
void BubbleSort(List ints)
{
    bool isOK = false;
    do
    {
        isOK = true;
        for (int i = 0; i < ints.Count - 1; i++)
        {
            if (ints[i] > ints[i + 1])
            {
                int temp = ints[i];
                ints[i] = ints[i + 1];
                ints[i + 1] = temp;
                isOK = false;
            }
        }
    }
    while (!isOK);
}

/// 
/// 简单选择排序
/// 
void SimpleSort(List ints)
{
    for (int i = 0; i < ints.Count; i++)
    {
        int min = ints[i];
        int minIndex = i;
        for (int j = i + 1; j < ints.Count; j++)
        {
            if (ints[j] < min)
            {
                min = ints[j];
                minIndex = j;
            }
        }
        if (min != ints[i])
        {
            int temp = ints[i];
            ints[i] = ints[minIndex];
            ints[minIndex] = temp;
        }
    }
}

//快速排序
void QuickSort(List numbers, int left, int right)
{
    //左边索引小于右边,则还未排序完成   
    if (left < right)
    {
        //取中间的元素作为比较基准,小于他的往左边移,大于他的往右边移   
        int middle = numbers[(left + right) / 2];
        int i = left - 1;
        int j = right + 1;
        while (true)
        {
            while (numbers[++i] < middle && i < right) ;
            while (numbers[--j] > middle && j > 0) ;
            if (i >= j)
                break;
            Swap(numbers, i, j);

        }
        QuickSort(numbers, left, i - 1);
        QuickSort(numbers, j + 1, right);
    }
}
//交换位置
void Swap(List numbers, int i, int j)
{
    int number = numbers[i];
    numbers[i] = numbers[j];
    numbers[j] = number;
}

 

你可能感兴趣的:(unity,C#)