现在的位置: 首页 > 综合 > 正文

C# 排序–小测试

2012年12月13日 ⁄ 综合 ⁄ 共 1894字 ⁄ 字号 评论关闭
代码

            int[] source = new int[] { 1343453 };
            printInt(source);
            
//从小到大排序
            /*   //选择
            for (int i = 0; i < source.Length; i++)
            {
                for (int j = i + 1; j < source.Length; j++)
                {
                    //前面的比后面的大,则调换位置
                    if (source[i] > source[j])
                    {
                        int temp = source[i];
                        source[i] = source[j];
                        source[j] = temp;
                    }
                }
            }
*/
            
/*  //冒泡
            int j = 1;
            bool done = false;
            while(j<source.Length && !done)
            {
                done = true;
                for (int i = 0; i < source.Length-1; i++)
                {    
                    //[相邻的俩比较]前面的比后面的大,则调换前后位置
                    if (source[i] > source[i+1])
                    {
                        done =false;
                        int temp = source[i];
                        source[i] = source[i+1];
                        source[i+1] = temp;
                    }                 
                }
                j++;
            }
*/
            
//插入法排序
            for (int i = 1; i < source.Length ; i++)
            {
                
int temp = source[i];
                
int j = i;
                
while (j>0 && source[j-1]>temp)
                {
                    source[j] 
= source[j - 1];
                    j
--;
                }
                source[j] 
= temp;
            }

测试下排序.

1。数组定义,并初始化int[] source = new int[] { 1, 34, 3, 45, 3 };

2。打印数组,用for循环打印

3。排序思想[以从小到大为例]

(1)i=0;i<长度;i++ ; { j =i+1;j<长度;j++ .拿第i个与第i之后的所有(j)依次比较,若i处大于后者,则调换位置----一轮下来,i处放的是未排序的数值中最小的.--称选择排序

(2)j=1;flag=fasle while(j<长度且flag为false){for(i=1;i<长度-1;i++) 哪相邻的俩(i与i+1)比较,小的放前面----一轮下来,最大的被放到了最后.---称为冒泡排序

(3)i=1;i<长度,i+{记下i处值,j=i while(i之前(j处)若有比i处大的,则让i处值等于较大的 ) j处等于i处值原始值----一轮下来,i处是已排序的i个值中最大的--称插入排序

抱歉!评论已关闭.