在游戏领域,算法也是一部分,于是开始了学习算法,
下面写个C#的快速排序
unity的
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ValueAnd : MonoBehaviour { // Use this for initialization void Start() { int[] arr = { 1, 2, 3 ,4, 5, 6, 7,8}; bulle(arr); foreach (var i in arr) { Debug.Log(i); } } void changeOther(int[] arr, int a, int b) //it’s nice { arr[a] = arr[a] + arr[b]; //总和 arr[b] = arr[a] - arr[b]; //总和-b 得a arr[a] = arr[a] - arr[b]; //同理得b } void bulle(int[] arr) { int lenth = arr.Length; for (int outSet = lenth - 1; outSet >= 1; outSet--) { bool First = true; for (int inner = 0; inner < lenth - 1; inner++) { Debug.Log(inner); if (arr[inner] > arr[inner + 1]) { changeOther(arr, arr[inner], arr[inner + 1]); if (First) First = false; } } Debug.Log(outSet); if (First){ break; } } } }
两种换值方法, 一种是 int 一个 temp,然后交换,
int a; int b; int temp;
temp=a;a=b;b=temp;
还可以,
temp=a+b;
b=temp-b;
a=temp-b;
First是标记是否第一次