簡單排序的幾種方式
冒泡排序

運作方式
外層for循環定義循環最大上限,每次循環下減
内層for循環,從0到外層循環的最大值,進行周遊
核心:if 條件判斷,将相鄰的兩個數組進行交換```
```class Change {
public Change(int[] arr) {
for (int i = arr.Count() - 1; i >= 0; i--) //減1為了防止數組下标越界`
{
for (int j = 0; j < i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = 0;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
foreach (int item in arr){
Console.Write(item+" ");
}
}
}
class Program
{
static void Main(string[] args)
{
int[] arr = { 10, 20, 55, 77, 1, 5 };
Change a = new Change(arr);
Console.ReadKey();
}
}
插入排序
運作方式
從前面挑出一個數 ,與被挑出數的前一個進行比較,假如小于前面的數,則交換位置,前面的所有數都和這個數作比較,假如都小于這個數,則跳過循環,進行下一次循環。
class Program
{
static void Main(string[] args)
{
int[] arr = { 10, 20, 55, 77, 1, 5 };
Change a = new Change(arr);
Console.ReadKey();
}
}
class Change {
public Change(int[] arr) {
for (int i = 1; i < arr.Length; i++)
for (int j = i; j > 0; j--)
{
if (arr[j] < arr[j - 1])
{
int temp = 0;
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
foreach (int item in arr)
{
Console.Write(item + " ");
}
}
}
}
```csharp
在這裡插入代碼片