您的位置:首页 > 其它

一直分不清选择排序和冒泡排序,网上也好多都是模棱两可的,按自己的理解,总结了个小demo以作记录,希望批评指正

2018-03-02 00:16 549 查看
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; //然后把临时位置的那个大数赋给后一个
}
}
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐