帮我写一个包含所有排序的C#脚本
时间: 2023-08-28 07:35:23 浏览: 44
以下是一个包含所有排序算法的C#脚本,你可以根据需要选择其中的排序算法:
```csharp
using System;
class SortingAlgorithms
{
static void Main()
{
int[] arr = { 5, 2, 7, 4, 1, 6, 3, 8 };
Console.WriteLine("Original array:");
PrintArray(arr);
Console.WriteLine("\nSorted array using Bubble Sort:");
BubbleSort(arr);
PrintArray(arr);
Console.WriteLine("\nSorted array using Selection Sort:");
SelectionSort(arr);
PrintArray(arr);
Console.WriteLine("\nSorted array using Insertion Sort:");
InsertionSort(arr);
PrintArray(arr);
Console.WriteLine("\nSorted array using Quick Sort:");
QuickSort(arr, 0, arr.Length - 1);
PrintArray(arr);
Console.WriteLine("\nSorted array using Merge Sort:");
MergeSort(arr, 0, arr.Length - 1);
PrintArray(arr);
}
static void BubbleSort(int[] arr)
{
int temp;
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = 0; j < arr.Length - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
static void SelectionSort(int[] arr)
{
int temp, minIndex;
for (int i = 0; i < arr.Length - 1; i++)
{
minIndex = i;
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
static void InsertionSort(int[] arr)
{
int j, temp;
for (int i = 1; i < arr.Length; i++)
{
temp = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > temp)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
static void QuickSort(int[] arr, int left, int right)
{
if (left < right)
{
int pivot = Partition(arr, left, right);
QuickSort(arr, left, pivot - 1);
QuickSort(arr, pivot + 1, right);
}
}
static int Partition(int[] arr, int left, int right)
{
int pivot = arr[right];
int i = left - 1;
int temp;
for (int j = left; j < right; j++)
{
if (arr[j] < pivot)
{
i++;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
temp = arr[i + 1];
arr[i + 1] = arr[right];
arr[right] = temp;
return i + 1;
}
static void MergeSort(int[] arr, int left, int right)
{
if (left < right)
{
int mid = (left + right) / 2;
MergeSort(arr, left, mid);
MergeSort(arr, mid + 1, right);
Merge(arr, left, mid, right);
}
}
static void Merge(int[] arr, int left, int mid, int right)
{
int[] temp = new int[arr.Length];
int i = left;
int j = mid + 1;
int k = left;
while (i <= mid && j <= right)
{
if (arr[i] <= arr[j])
{
temp[k] = arr[i];
i++;
}
else
{
temp[k] = arr[j];
j++;
}
k++;
}
while (i <= mid)
{
temp[k] = arr[i];
i++;
k++;
}
while (j <= right)
{
temp[k] = arr[j];
j++;
k++;
}
for (int x = left; x <= right; x++)
{
arr[x] = temp[x];
}
}
static void PrintArray(int[] arr)
{
foreach (int i in arr)
{
Console.Write(i + " ");
}
}
}
```
这个脚本包含了冒泡排序、选择排序、插入排序、快速排序和归并排序。你可以根据需要在脚本中选择一个或多个排序算法。