C#에서 정렬

PHPz
풀어 주다: 2024-09-03 15:24:11
원래의
359명이 탐색했습니다.

C#에서 정렬은 컬렉션의 콘텐츠를 특정 순서로 정렬하는 프로세스입니다. 컬렉션은 배열, 목록 또는 기타 데이터 그룹일 수 있습니다. 컬렉션에는 복합 유형뿐만 아니라 단순 유형의 요소도 포함될 수 있습니다. 단순 유형은 정수, 문자열, 부동 소수점 숫자 등의 컬렉션일 수 있습니다. 복합 유형은 직원, 학생 등과 같은 사용자 정의 유형의 개체 컬렉션일 수 있습니다. 복합 유형은 중첩되는 경우가 많습니다. 객체에는 여러 속성이 있을 수 있습니다.

  • 간단형
    • 정수 컬렉션 - {1, 2, 3, 4, 5}
    • 문자열 컬렉션 – {“Mark”, “Jamie”, “Anna”}
  • 복합형
    • { [이름: “Mark”, 직원 ID: “123”, 사무실: “London”],
      [이름: “Jane”, 직원 ID: “456”, 사무실: “NY”],
      [이름: “Annie”, 사원 ID: “789”, 사무실: “Sydney”] }

C#에서는 컬렉션을 정렬하는 메서드가 내장되어 있습니다. 배열, 목록 또는 일반 컬렉션이든 C# Sort() 메서드는 제공된 비교자를 기반으로 정렬할 수 있습니다. 내부적으로 .Net 구현은 Quicksort 알고리즘을 사용하여 C#에서 컬렉션을 정렬합니다. 이에 대해서는 기사의 다음 섹션에서 자세히 논의하겠습니다.

C#에서는 정렬이 어떻게 수행되나요?

앞서 설명한 것처럼 .Net 프레임워크는 Quicksort 접근 방식을 사용하여 C# 컬렉션의 요소를 정렬합니다. 그렇다면 퀵소트란 무엇일까요?

퀵 정렬은 분할 정복 전략을 따릅니다. 즉, 정렬 알고리즘은 피벗 요소를 선택하고 피벗 요소를 기준으로 배열을 나눕니다. 피벗보다 작은 요소는 피벗 앞에 배치됩니다. 피벗보다 큰 요소는 피벗 뒤에 배치됩니다. 이렇게 하면 피벗 요소가 정렬됩니다. 또한 배열은 피벗보다 작은 요소와 피벗보다 큰 요소 두 개로 나뉩니다. 다음으로 알고리즘은 두 어레이에 대해 동일한 접근 방식을 따릅니다.

이에 대한 그림은 아래에서 볼 수 있습니다.

정렬되지 않은 배열 – 18, 5, 16, 23, 50, 32

1단계(피벗 = 32) – 18, 5, 16, 23, 32, 50

2a단계
정렬되지 않은 배열 – 18, 5, 16, 23
피벗 = 23
부분적으로 정렬된 배열 – 18, 5, 16, 23

2b단계
정렬되지 않은 배열 – 50
피벗 = 50
부분적으로 정렬된 배열 – 50

3a단계
정렬되지 않은 배열 – 18, 5, 16
피벗 = 16
부분적으로 정렬된 배열 – 5, 16, 18

정렬된 배열 – 5, 16, 18, 23, 32, 50

따라서 Quicksort에는 피벗 선택과 배열 분할이라는 두 가지 주요 프로세스가 있습니다. 알고리즘의 구현은 피벗 선택에 따라 달라집니다. 첫 번째 요소이거나 마지막 요소이거나 임의의 요소이거나 배열의 중앙값일 수 있습니다. 분할이 완료되고 피벗이 올바른 위치에 배치되면 모든 요소가 정렬될 때까지 분할된 배열에 대해 알고리즘이 반복적으로 호출됩니다.

C#에서 정렬을 하면 안정정렬과 불안정퀵정렬이라는 개념이 나옵니다. 안정적인 Quicksort에서는 두 요소가 동일하면 원래 배열의 순서가 유지됩니다. 그렇지 않으면 불안정한 퀵소트에 있습니다. C# 구현에서는 불안정한 Quicksort를 사용합니다.

C#의 정렬 유형

이 기사 섹션에서는 주로 C#의 두 가지 유형의 컬렉션인 배열과 목록에 중점을 둘 것입니다. C#에서 배열과 목록을 정렬하는 방법을 자세히 살펴보겠습니다. 다음 섹션에서는 몇 가지 예를 들어 설명하겠습니다.

1. C#에서 배열 정렬

C#에서 배열을 정렬할 수 있는 다양한 방법을 살펴보겠습니다.

아. 기본 비교기 사용

기본 Sort() 메서드입니다. 메서드에 비교자가 명시적으로 전달되지 않으면 C#에서는 오름차순을 사용하여 요소를 정렬합니다.

코드:

using System;
public class Program
{
public static void Main()
{
String[] strArray = {"I", "Am", "Learning", "Array", "Sorting","In", "C#"};
int[] intArray = {23, 76, 12, 43, 90, 30};
Array.Sort(strArray);
Array.Sort(intArray);
Console.WriteLine("Sorted String Array:\n");
DisplayArray(strArray);
Console.WriteLine("\n\n\nSorted Integer Array:\n");
DisplayArray(intArray);
}
static void DisplayArray(string[] arr)
{
foreach (string a in arr)
{
Console.Write(a + "\t");
}
}
static void DisplayArray(int[] arr)
{
foreach (int a in arr)
{
Console.Write(a + "\t");
}
}
}
로그인 후 복사

출력:

C#에서 정렬

ㄴ. 사용자 정의 비교기 사용

Sort() 메소드에 자체 사용자 정의 비교자를 제공할 수도 있습니다. 이렇게 하면 C# 컴파일러가 기본 비교자 대신 사용자 지정 비교자를 사용하도록 지시합니다.

사용자 정의 비교자를 생성하려면 IComparer 인터페이스에서 Compare() 메서드를 구현해야 합니다. 아래 코드는 요소를 내림차순으로 정렬하는 비교자를 생성하는 방법을 보여줍니다.

클래스를 생성하고 IComparer 인터페이스에서 상속한 후 Compare() 메서드를 구현하고 이를 재정의하여 요소를 내림차순으로 비교했습니다.

코드:

using System;
public class DescendingComparer : System.Collections.IComparer
{
public int Compare(Object a, Object b)
{
return (new System.Collections.CaseInsensitiveComparer()).Compare(b, a);
}
}
public class Program
{
public static void Main()
{
String[] strArray = {"I", "Am", "Learning", "Array", "Sorting","In", "C#"};
int[] intArray = {23, 76, 12, 43, 90, 30};
Array.Sort(strArray, new DescendingComparer());
Array.Sort(intArray, new DescendingComparer());
Console.WriteLine("Sorted String Array in Descending Order:\n");
DisplayArray(strArray);
Console.WriteLine("\n\n\nSorted Integer Array in Desc Order:\n");
DisplayArray(intArray);
}
static void DisplayArray(string[] arr)
{
foreach (string a in arr)
{
Console.Write(a + "\t");
}
}
static void DisplayArray(int[] arr)
{
foreach (int a in arr)
{
Console.Write(a + "\t");
}
}
}
로그인 후 복사

출력:

C#에서 정렬

c. Using Key-Value Pairs

C# also provides a way to sort one array using key values from another array. The example below has key-value pairs of first names and last names of people. We would sort them by both first and last names using the Sort() method.

Code:

using System;
public class Program
{
public static void Main()
{
String[] firstNames = {"Tom", "Jack", "Anna", "Veronica", "Jessica", "Mike"};
String[] lastNames = {"Phelps", "Anderson", "Spectre", "Clarke",   "Williams", "Fonseca"};
Array.Sort(firstNames, lastNames);
Console.WriteLine("Sorted by First Names:\n");
DisplayArray(firstNames, lastNames);
Array.Sort(lastNames, firstNames);
Console.WriteLine("\n\nSorted by Last Names:\n");
DisplayArray(firstNames, lastNames);
}
static void DisplayArray(string[] arr1, string[] arr2)
{
for (int i = 0; i < arr1.Length; i++)
{
Console.WriteLine(arr1[i] + " " + arr2[i]);
}
}
}
로그인 후 복사

Output:

C#에서 정렬

2. Sorting a List in C#

Let us look at the different ways in which we can sort a list in C#.

Note – To use Lists in C#, including the library System.Collections.Generic.
a. Using Default Comparer

This is the default sort() method. if no comparer is explicitly passed to the method, c# uses the ascending order to arrange the elements.

Code:

public class Program
using System.Collections.Generic;
{
public static void Main()
{
String[] strArray = {"I", "Am", "Learning", "Array", "Sorting", "In", "C#"};
List<string> strList = new List<string>(strArray);
int[] intArray = {23, 76, 12, 43, 90, 30};
List<int> intList = new List<int>(intArray);
strList.Sort();
intList.Sort();
Console.WriteLine("Sorted String List:\n");
DisplayList(strList);
Console.WriteLine("\n\n\nSorted Integer List:\n");
DisplayList(intList);
}
static void DisplayList(List<string> myList)
{
foreach (string a in myList)
{
Console.Write(a + "\t");
}
}
static void DisplayList(List<int> myList)
{
foreach (int a in myList)
{
Console.Write(a + "\t");
}
}
}
로그인 후 복사

Output:

C#에서 정렬

b. Using Custom Comparer

We can also provide our own custom comparer to the sort() method. This would instruct the c# compiler to use the custom comparer instead of the default one.

To create a custom comparer, we need to implement the Compare() method from the IComparer interface. The code below demonstrates how to create a comparer that would sort the elements in descending order.

We created a class, inherited it from the IComparer interface, implemented the Compare() method and overrode it to compare the elements in descending order.

Code:

using System;
using System.Collections.Generic;
public class LengthComparer : IComparer<string>
{
public int Compare(string a, string b)
{
return (a.Length.CompareTo(b.Length));
}
}
public class DigitSumComparer : IComparer<int>
{
public int Compare(int a, int b)
{
int sum_a = 0;
int sum_b = 0;
while (a > 0)
{
sum_a += (a % 10);
a /= 10;
}
while (b > 0)
{
sum_b += (b % 10);
b /= 10;
}
return (sum_a.CompareTo(sum_b));
}
}
public class Program
{
public static void Main()
{
LengthComparer lc = new LengthComparer();
DigitSumComparer dsc = new DigitSumComparer();
String[] strArray = {"I", "Am", "Learning", "Array", "Sorting", "In", "C#"};
List<string> strList = new List<string>(strArray);
int[] intArray = {23, 76, 12, 43, 90, 30};
List<int> intList = new List<int>(intArray);
strList.Sort(lc);
intList.Sort(dsc);
Console.WriteLine("Sorted String List by Length:\n");
DisplayList(strList);
Console.WriteLine("\n\n\nSorted Integer List by Sum of Digits:\n");
DisplayList(intList);
}
static void DisplayList(List<string> myList)
{
foreach (string a in myList)
{
Console.Write(a + "\t");
}
}
static void DisplayList(List<int> myList)
{
foreach (int a in myList)
{
Console.Write(a + "\t");
}
}
}
로그인 후 복사

Output:

C#에서 정렬

Sorting Complex List Types

Complex List Types are user-defined lists. To be more precise, they are lists of objects of user-defined classes. Being user-defined, the objects are a mixture of various primitive types. It is difficult to sort a complex list type. C# compiler expects each complex class to inherit from the IComparable interface and define the method CompareTo(). This method contains the instructions on how to compare the elements of the list for sorting.

In the example below, we define a user-defined class of Employees and sort the Employee objects based on their IDs.

Example #1

Code:

using System;
using System.Collections.Generic;
public class Employee : IComparable<Employee>
{
public int id {get;set;}
public string name{get;set;}
public double salary{get;set;}
public int CompareTo(Employee e)
{
return this.id.CompareTo(e.id);
}
}
public class Program
{
public static void Main()
{
List<Employee> emps = new List<Employee>();
emps.Add(new Employee()
{id = 123, name = "Tom Phelps", salary = 20000.00});
emps.Add(new Employee()
{id = 897, name = "Jack Anderson", salary = 40050.50});
emps.Add(new Employee()
{id = 342, name = "Anna Spectre", salary = 31030.89});
emps.Add(new Employee()
{id = 219, name = "Veronica Clarke", salary = 66333.66});
emps.Add(new Employee()
{id = 642, name = "Jessica Williams", salary = 50505.05});
emps.Add(new Employee()
{id = 923, name = "Mike Fonseca", salary = 76543.21});
Console.WriteLine("Original Employee List:\n");
DisplayList(emps);
emps.Sort();
Console.WriteLine("\n\nSorted Employee List by IDs:\n");
DisplayList(emps);
}
static void DisplayList(List<Employee> emp)
{
foreach (Employee e in emp)
{
Console.WriteLine("Id: " + e.id + ", Name: " + e.name + ",  Salary: " + e.salary);
}
}
}
로그인 후 복사

Output:

 C#에서 정렬

Now, the obvious question that comes to mind is that what if we want to sort the objects of Employee class based on some other property? This is possible. We would need to implement the IComparer interface. Let us take a look at the example below to understand.

Example #2

Code:

using System;
using System.Collections.Generic;
public class Employee
{
public int id {get;set;}
public string name{get;set;}
public double salary{get;set;}
}
public class SortByName : IComparer<Employee>
{
public int Compare(Employee e1, Employee e2)
{
return e1.name.CompareTo(e2.name);
}
}
public class SortBySalary : IComparer<Employee>
{
public int Compare(Employee e1, Employee e2)
{
return e1.salary.CompareTo(e2.salary);
}
}
public class Program
{
public static void Main()
{
SortByName sbn = new SortByName();
SortBySalary sbs = new SortBySalary();
List<Employee> emps = new List<Employee>();
emps.Add(new Employee()
{id = 123, name = "Tom Phelps", salary = 20000.00});
emps.Add(new Employee()
{id = 897, name = "Jack Anderson", salary = 40050.50});
emps.Add(new Employee()
{id = 342, name = "Anna Spectre", salary = 31030.89});
emps.Add(new Employee()
{id = 219, name = "Veronica Clarke", salary = 66333.66});
emps.Add(new Employee()
{id = 642, name = "Jessica Williams", salary = 50505.05});
emps.Add(new Employee()
{id = 923, name = "Mike Fonseca", salary = 76543.21});
emps.Sort(sbn);
Console.WriteLine("Sorted Employee List by Names:\n");
DisplayList(emps);
emps.Sort(sbs);
Console.WriteLine("\n\nSorted Employee List by Salaries:\n");
DisplayList(emps);
}
static void DisplayList(List<Employee> emp)
{
foreach (Employee e in emp)
{
Console.WriteLine("Id: " + e.id + ", Name: " + e.name + ",  Salary: " + e.salary);
}
}
}
로그인 후 복사

Output:

C#에서 정렬

Conclusion

So, this article covered in-depth on how to sort collections in C#. We focused majorly on Arrays and Lists since these two covers all the primitive types as well. Once the concept of Sorting in C# is very well understood, it becomes easy to implement sorting in other collections such as Enumerations, Dictionaries, etc. After completing this article, it is recommended to explore the MSDN documentation for more implementations of Sorting in C#.

위 내용은 C#에서 정렬의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!