namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] arr = { 1, 4, 2, 43, 5, 61, 89, 34, 67, 32, 40 };
//調用冒泡排序方法
bubblesort(arr);
//調用選擇排序方法,並輸出。
SumSort mysort = new SumSort();
mysort.PopSort(arr);
for (int i = 0; i < arr.Length; i++)
{
Console.Write("第{0}位是{1}\n", i + 1, arr[i]);
}
Console.WriteLine();
}
//冒泡排序 降序排列
static void bubblesort(int[] a)
{
int i, j;
int tmp;
int flag = 0; //標記,如果第一次循環比較時沒有發生交換,則說明數組是升序排序,不用排序,提前結束循環。
for (i = 0; i < a.Length; i++) //外層循環數組長度
{
for (j = 0; j < a.Length - 1 - i; j++) //內層循環控制每次循環裏比較的次數。
{
if (a[j] > a[j + 1])
{
tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
flag = 1;
}
}
if (0 == flag)
{
Console.WriteLine("升序排序");
break;
}
else
{
Console.WriteLine(a[j]);
}
}
}
}
public class SumSort
{
//選擇排序 升序排列
public void PopSort(int[] list)
{
int i, j, temp; //先定義一下要用的變量
for (i = 0; i < list.Length - 1; i++)
{
for (j = i + 1; j < list.Length; j++)
{
if (list[i] > list[j]) //如果第二個小於第一個數
{
temp = list[i]; //把大的數放在一個臨時存儲位置
list[i] = list[j]; //然後把小的數賦給前一個,保證每趟排序前面的最小
list[j] = temp; //然後把臨時位置的那個大數賦給後一個
}
}
}
}
}
}
一直分不清選擇排序和冒泡排序,網上也好多都是模棱兩可的,按自己的理解,總結了個小demo以作記錄,希望批評指正
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.