在unity里实现冒泡排序,

先说一下自己的想法,冒泡排序就是随机生成10个在100内的随机数,然后按大到小,排序,基本就是使用for()循环来实现,数字的随机生成,用unity里的随机数的函数来实现就Random.Ranre()

1:先在unity里创建一个text的ui界面用来显示生成的数字和一个·按钮来启动开始的生成的十个数子字

 2:在unity文件项目里创建C#脚本,用来写实现效果的代码

3:进入代码编辑页面,先将我们的unity的ui这个类添加到现在使用的代码上,然后我们再根据需要创建一个text的组件,和一个int类型的数组,数组的长度设为10个,和一个字符串类型的变量

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;//添加ui类

public class NewBehaviourScript : MonoBehaviour
{
    public Text shuz;
    public static int[] a = new int[10];
    partial string str;


void Start
{

}
void Update
{
}

}

4:为实现点击按钮的生成数字的效果,我们在外面创建一个方法,在这个方法里来实现十个数字的随机赋值和输出

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

public class NewBehaviourScript : MonoBehaviour
{
    public Text shuz;
    public int[] a = new int[10];
    
    string str;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void Button()
    {
        for (int i = 0; i < a.Length; i++)//我们先用for循环来实现数组长度的循环
        {
            a[i] = Random.Range(0, 100);//Random.Range()随机在0到100之间赋值一个数字
            str = "";//初始化当前为空的字符串
            foreach(int c in a)//数组的循环将数组里每一个赋值的数输出出来,达到十个随机数的效果
            {
                shuz.text =str+=c + ",";
            }
        }
    }
}

5:将前面写好的代码拖入到unity里并设置好,并将我们的text组件拖入他的位置

 

 这样就基本实现了按钮输出十个随机数的效果

 到这里就实现了冒泡排序的前半部分,接下来实现后半部分,我的想法就是我们在外面的大循环里再循环一个用来比较第一个数和第二个数的大小,如果前面的数比后面的数大哪就用一个数据存储大的数然后将小的数赋值给前面的后面存储的大的数给后面,就实现了比较大小并排列的效果

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

public class NewBehaviourScript : MonoBehaviour
{
    public Text shuz;
    public static int[] a = new int[10];
    
    string str;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void Button()
    {
        for (int i = 0; i < a.Length; i++)
        {
            a[i] = Random.Range(0, 100);
            str = "";

            for (int e = 0; e <i; e++)
            {
                if (a[e] > a[i])
                {
                    int h = a[e];
                    a[e] = a[i];
                    a[i] = h;
                   
                }
            }
            foreach (int c in a)
            {
                shuz.text = str += c + ",";

            }

        }
       
    }
}

 这样输出来的十个数字就是按大小排列好了的输出,冒泡排序就做好了,当然做的方法有很多种,这只是我的想法,仅供参考

猜你喜欢

转载自blog.csdn.net/weixin_63794834/article/details/124990377