C# 排序–小測試

來源:互聯網
上載者:User
代碼

            int[] source = new int[] { 1, 34, 3, 45, 3 };
            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個值中最大的--稱插入排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.