그래서 저는이 거품 종류를 가지고 있습니다. 처음으로 하나를 만들려고했는데 이것이 제가 가진 것입니다. 어떤 이유로 이상한 방식으로 배열을 인쇄하고 있습니다. 내가 아는 한 문자로 정렬해야합니다.
LINQ 또는 Array.Sort ();를 사용하지 않고 어떻게 버블 정렬을 올바르게 수행합니까? 이것은 학교용이므로 버블 정렬 알고리즘을 수행해야합니다.
다음은 출력되는 이미지입니다.
class Program
{
static string[] animals = new string[] { "cat", "elephant", "tiger", "fish", "dolphin", "giraffe", "hippo", "lion", "rat", "string ray" };
static void Main(string[] args)
{
BubbleSort();
Console.ReadLine();
}
private static void BubbleSort()
{
bool swap;
string temp;
string[] animals = new string[] { "cat", "elephant", "tiger", "fish", "dolphin", "giraffe", "hippo", "lion", "rat", "string ray" };
for (int index = 0; index < (animals.Length - 1); index++)
{
if (string.Compare(animals[index], animals[index + 1], true) < 0) //if first number is greater then second then swap
{
//swap
temp = animals[index];
animals[index] = animals[index + 1];
animals[index + 1] = temp;
swap = true;
}
}
foreach (string item in animals)
{
Console.WriteLine(item);
}
}
}
Bubblesort의 경우 배열을 한 번이 아니라 여러 번 전달하기 때문에 두 개의 중첩 루프가 필요합니다.
private static void BubbleSort()
{
string temp;
string[] animals = new string[] { "cat", "elephant", "tiger", "fish", "dolphin", "giraffe", "hippo", "lion", "rat", "string ray" };
for (int i = 1; i < animals.Length; i++)
{
for (int j = 0; j < animals.Length - i; j++)
{
if (string.Compare(animals[j], animals[j + 1], StringComparison.Ordinal) <= 0) continue;
temp = animals[j];
animals[j] = animals[j + 1];
animals[j + 1] = temp;
}
}
foreach (string item in animals)
{
Console.WriteLine(item);
}
}
추신 : 다음에 검색을 조금 더 사용 하십시오 . 위의 코드는 http://stackoverflow.com/questions/38624840/bubble-sort-string-array-c-sharp 에서 거의 100 % 가져 왔습니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다