1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test : MonoBehaviour { void Start() { List<int> datas = new List<int>(); for (int i = 0; i < 100; i++) { datas.Add(Random.Range(0, 100)); } Quick(datas,0,datas.Count-1); for (int i = 0; i < datas.Count; i++) { Debug.Log(datas[i]); } } void Quick(List<int> datas,int left,int right) { int pL = left; int pR = right; int pivot = datas[(left+right)/2]; while (pL <= pR) { while (datas[pL] < pivot) pL++; while (datas[pR] > pivot) pR--; if (pL <= pR) { SwapList(datas, pL, pR); pL++; pR--; } } if (left < pR) Quick(datas, left, pR); if (pL < right) Quick(datas, pL, right); } void SwapList(List<int> datas, int a, int b) { int temp = datas[a]; datas[a] = datas[b]; datas[b] = temp; } } | cs |
유니티에서 작성했다.
위와 같이 재귀로 구현하는 방법이 있고,재귀없이 스택을 활용해도 가능 한데, 퀵정렬 같은 경우에는
재귀 없이 짜는것 보다, 재귀가 훨씬 간결하고 깔끔한 것 같다.
재귀가 복잡하고 보기 어려운 것인줄만 알았는데,
이번 경우를 보면서 오히려 재귀가 더 간결하게 보일수도 있다는 것을 알게 됐다.
앞으로 재귀가 나온다고 해서 무작정 겁먹지 말지어다.ㅋㅋ
'프로그래밍 > C#' 카테고리의 다른 글
try catch 성능 (0) | 2018.03.21 |
---|---|
using , Dispose() (0) | 2018.03.21 |
가중치 랜덤 생성 (0) | 2018.03.13 |
이진탐색 (0) | 2018.03.11 |
c# string으로 class 인스턴스 생성하기 (0) | 2017.09.04 |