정렬 Array.Sort, Array.Reverse
//정렬 Array.Sort
//int 정렬
int[] intArray = { 1, 40, 34, 23, 56, 53, 87, 85, 32, 10 }; //int 배열
Array.Sort(intArray); // 오름 차순으로 정렬 되어 고정(1 10 23 32 34 40 53 56 85 87)
Array.Reverse(intArray); // 역정렬 되어 고정(87 85 56 53 40 34 32 23 10 1)
//--------------------------------------------------------//
//별도의 class 정렬
class Pistol : IComparable<Pistol> //Sort를 하려면 IComparable<T>가 있어야 한다. Interface 이다.
{
public int damage = 1; //데미지 변수
public Pistol(int power) //생성자
{
damage = power;
}
//IComparable<T> 를 상속받고 비교하는 함수를 만든다.
public int CompareTo(Pistol other)//인자는 T값(템플릿)
{
//데미지 별로 정렬 하겠다.
//Sort할 때 앞으로 갈껀 -1, 뒤는 1, 같으면 0
if(this.damage < other.damage)
{
//쟈기가 적으면 앞으로
return -1;
}
else if(this.damage > other.damage)
{
//쟈기가 크면 뒤로
return 1;
}
//같으면 0
return 0;
}
}
//main에서........
Pistol[] guns = new Pistol[10]; //class 배열 공간 생성
//랜덤객체 생성
Random random = new Random();
for (int i = 0; i < guns.Length; ++i )
{
//데미지 랜덤 생성
guns[i] = new Pistol(random.Next(100) + 1);
}
Array.Sort(guns); //class 배열 정렬 가능
'공부 > C#' 카테고리의 다른 글
C#에서의 struct(구조체)와 class - 메모리 구조 차이, Boxing, Unboxing 예제소스 (0) | 2016.05.11 |
---|---|
C#에서의 struct(구조체)와 class - 메모리 구조 차이, Boxing, Unboxing 개념 (0) | 2016.05.11 |
추상 클래스, 추상 함수(abstract), 인터페이스(interface) (0) | 2016.05.09 |
랜덤 (0) | 2016.05.09 |
함수인자 ref, out (0) | 2016.05.09 |