您好,登錄后才能下訂單哦!
工作之余,把寫代碼過程中比較重要的一些代碼段收藏起來,如下的代碼是關于使用幾種常用排序方法對C#數組進行排序的代碼,希望能對各朋友有幫助。
using System;
namespace DataStruct
{
public class Sorter
{
public static void BubbleSort(int[] list)
{
for (int i = 0; i < list.Length; i++)
{
for (int j = i; j < list.Length; j++)
{
if (list[i] < list[j])
{
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
public static void InsertionSort(int[] list)
{
for (int i = 1; i < list.Length; i++)
{
int t = list[i];
int j = i;
while ((j > 0) && (list[j - 1] > t))
{
list[j] = list[j - 1];
--j;
}
list[j] = t;
}
}
public static void SelectionSort(int[] list)
{
int min;
for (int i = 0; i < list.Length - 1; i++)
{
min = i;
for (int j = i + 1; j < list.Length; j++)
{
if (list[j] < list[min])
min = j;
}
int t = list[min];
list[min] = list[i];
list[i] = t;
}
}
public static void ShellSort(int[] list)
{
int inc;
for (; inc > 0; inc /= 3)
{
for (int i = inc + 1; i <= list.Length; i += inc)
{
int t = list[i - 1];
int j = i;
while ((j > inc) && (list[j - inc - 1] > t))
{
list[j - 1] = list[j - inc - 1];
j -= inc;
}
list[j - 1] = t;
}
}
}
private static void Swap(ref int l, ref int r)
{
int s;
s = l;
l = r;
r = s;
}
public static void Sort(int[] list, int low, int high)
{
int pivot;
int l, r;
int mid;
if (high <= low)
return;
else if (high == low + 1)
{
if (list[low] > list[high])
Swap(ref list[low], ref list[high]);
return;
}
mid = (low + high) >> 1;
pivot = list[mid];
Swap(ref list[low], ref list[mid]);
l = low + 1;
r = high;
do
{
while (l <= r && list[l] < pivot)
l++;
while (list[r] >= pivot)
r--;
if (l < r)
Swap(ref list[l], ref list[r]);
} while (l < r);
list[low] = list[r];
list[r] = pivot;
if (low + 1 < r)
Sort(list, low, r - 1);
if (r + 1 < high)
Sort(list, r + 1, high);
}
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。