排序方法(常用基础的排序)

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager_3 : MonoBehaviour
{
    public int[] arr_0 = { 10, 1, 8, 5, 2, 6, 3, 7, 9, 4 };//冒泡
    public int[] arr_1 = { 10, 1, 8, 5, 2, 6, 3, 7, 9, 4 };//选择
    public int[] arr_2 = { 10, 1, 8, 5, 2, 6, 3, 7, 9, 4 };//数组
    public List<int> list;//集合
    // Start is called before the first frame update
    void Start()
    {
        BubbleSort();

        SelectionSort();

        ArraySort();

        ListSort();

    }

    // Update is called once per frame
    void Update()
    {

    }

    //冒泡排序
    public void BubbleSort()
    {
        for (int i = 0; i < arr_0.Length - 1; i++)
        {
            for (int j = 0; j < arr_0.Length - 1 - i; j++)
            {
                if (arr_0[j] > arr_0[j + 1])//判断 如果第一个数大于第二个数就进行交换以此类推 从小到大 从大到小就反过来
                {
                    int temp = 0;
                    temp = arr_0[j];
                    arr_0[j] = arr_0[j + 1];
                    arr_0[j + 1] = temp;

                }
            }

        }
        Debug.Log("冒泡排序:从小到大");
        foreach (var item in arr_0)
        {
            Debug.Log(item);
        }

    }

    //选择排序
    public void SelectionSort()
    {
        for (int i = 0; i < arr_1.Length; i++)
        {
            int index = i;
            for (int j = i + 1; j < arr_1.Length; j++)
            {
                if (arr_1[index] > arr_1[j])
                {
                    index = j;
                }
            }

            int temp = 0;
            temp = arr_1[i];
            arr_1[i] = arr_1[index];
            arr_1[index] = temp;

        }

        Debug.Log("选择排序:从小到大");
        foreach (var item in arr_1)
        {
            Debug.Log(item);
        }

    }


    // Array.Sort排序
    public void ArraySort()
    {
        Array.Sort(arr_2);
        
        Debug.Log("ArraySort:从小到大");
        foreach (var item in arr_2)
        {
            Debug.Log(item);
        }
    }
    //List集合排序

    public void ListSort()
    {
        list = new List<int>() { 10, 1, 8, 5, 2, 6, 3, 7, 9, 4 };
        list.Sort((a, b) =>
        {

            if (a > b)
            {
                return 1;
            }
            else if (a == b)
            {
                return 0;
            }
            else
            {
                return -1;
            }
        });
        Debug.Log("List排序");
        Debug.Log(list.Count);
        foreach (var item in list)
        {
            Debug.Log(item);
        }


    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值