用c#分别写一个冒泡跟快排
时间: 2024-11-25 14:32:21 浏览: 3
C#实现冒泡堆栈队列
当然可以,下面是C#语言中使用冒泡排序和快速排序的简单示例:
**冒泡排序 (Bubble Sort)**
```csharp
using System;
public class BubbleSortExample
{
public static void Main()
{
int[] array = {5, 3, 8, 4, 2};
Console.WriteLine("Before sorting:");
PrintArray(array);
BubbleSort(array);
Console.WriteLine("\nAfter sorting:");
PrintArray(array);
}
public static void BubbleSort(int[] arr)
{
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = 0; j < arr.Length - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void PrintArray(int[] arr)
{
foreach (int num in arr)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
```
**快速排序 (Quick Sort)**
```csharp
using System;
public class QuickSortExample
{
public static void Main()
{
int[] array = {5, 3, 8, 4, 2};
Console.WriteLine("Before sorting:");
PrintArray(array);
QuickSort(array, 0, array.Length - 1);
Console.WriteLine("\nAfter sorting:");
PrintArray(array);
}
public static void QuickSort(int[] arr, int low, int high)
{
if (low < high)
{
int pivotIndex = Partition(arr, low, high);
QuickSort(arr, low, pivotIndex - 1);
QuickSort(arr, pivotIndex + 1, high);
}
}
private static int Partition(int[] arr, int low, int high)
{
int pivotValue = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++)
{
if (arr[j] < pivotValue)
{
i++;
// Swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Swap arr[i + 1] and arr[high] (or pivot)
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
public static void PrintArray(int[] arr)
{
foreach (int num in arr)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
```
这两个例子都是针对整数数组,并包含了对应的排序函数以及打印数组的方法。你可以将它们复制到C#项目中运行。
阅读全文