CShap 库排序 源代码
时间: 2023-11-09 12:12:09 浏览: 80
SOAP教程C++CSHAP
以下是一个使用C#编写的库排序源代码:
```
using System;
namespace LibrarySort
{
public static class SortLibrary
{
public static void BubbleSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void InsertionSort(int[] arr)
{
int n = arr.Length;
for (int i = 1; i < n; i++)
{
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
public static void SelectionSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
int minIndex = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
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 pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++)
{
if (arr[j] < pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp2 = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp2;
return i + 1;
}
public 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);
}
}
private static void Merge(int[] arr, int left, int mid, int right)
{
int n1 = mid - left + 1;
int n2 = right - mid;
int[] leftArr = new int[n1];
int[] rightArr = new int[n2];
for (int i = 0; i < n1; i++)
{
leftArr[i] = arr[left + i];
}
for (int j = 0; j < n2; j++)
{
rightArr[j] = arr[mid + 1 + j];
}
int k = left;
int i2 = 0, j2 = 0;
while (i2 < n1 && j2 < n2)
{
if (leftArr[i2] <= rightArr[j2])
{
arr[k] = leftArr[i2];
i2++;
}
else
{
arr[k] = rightArr[j2];
j2++;
}
k++;
}
while (i2 < n1)
{
arr[k] = leftArr[i2];
i2++;
k++;
}
while (j2 < n2)
{
arr[k] = rightArr[j2];
j2++;
k++;
}
}
}
}
```
该代码包含了几种经典的排序算法,包括冒泡排序、插入排序、选择排序、快速排序和归并排序。这些算法都是基于比较的排序算法,其时间复杂度一般为O(nlogn)或O(n^2)。其中,快速排序和归并排序是比较快速且常用的排序算法,而冒泡排序和插入排序则更适合于小规模数据的排序。该代码使用静态方法实现,可以方便地在其他程序中调用。
阅读全文