首页 > 代码库 > C#冒泡排序

C#冒泡排序

 

C#冒泡排序,转载自:http://bbs.it-home.org/forum-net-2.html不多解析自己看去吧 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace 冒泡排序
{
    class Program
    {
        static void Main(string[] args)
        {  
            int[]scores =new int[4];//定义数组 一共有四只小猴子
            int temp; //定义一个进行冒泡排序比较大小的临时变量
 
            Console.WriteLine("请输入4只小猴子的桃子数:");
            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine("请输入第{0}只小猴子的桃子数:",i+1);
                scores = int.Parse(Console.ReadLine());
            }
 
            //开始冒泡排序算法
            for (int i = 0; i < scores.Length-1; i++)
            {
                //将最大元素调换到最后
                for (int j = 0; j < scores.Length -1 -i; j++)
                {
                    if (scores[j] > scores[j + 1])
                    {
                        temp = scores[j];
                        scores[j] = scores[i + j];
                        scores[j + 1] = temp;
                    }
                }
            }
            //排序后输出
            Console.WriteLine("排序后的桃子为:");
            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine("{0}\t",scores);
            }
            Console.ReadLine();
 
        }
    }
}