close
C++排序
所謂排序,就是把陣列裡的數字從大到小或從小到大,身為程式人,小撇步你一定要學!!
 
舉ㄧ維陣列來說~~
如果你看不懂函數,請先看基本函數篇~~
#include <iostream>
using namespace std;
void selection_sort(int list[],int n);              //宣告函數
int main()
{
    int good[]={2,5,6,7,3,8,9,13,11,20,18,16,19};//good陣列的初始值
    selection_sort(good,13);                         //呼叫函數,放陣列和陣列個數
}
void selection_sort(int list[],int n)
{
    int i,j,k;
    for(i=n-1;i>=1;i--)                                        //選取陣列元素最大的值和未排序的陣列尾巴做交換
    {                                                                 ,這樣一直重複迴圈,直到i為0。這是巢狀for迴圈,是從
        int currentMax=list[0];                            陣列第一個元素到第n-1個元素,選取出最大值的陣列
        int currentMaxIndex=0;                         元素
        for(j=1;j<=i;j++)                                      //迴圈會從list[j]選取,從1開始到第i個最大的值給currentMax
        {                                                              。j是從1到i還未排序的陣列元素
            if(currentMax<list[j])
            {
                currentMax=list[j];
                currentMaxIndex=j;
            }
        }
        if(currentMaxIndex!=i)                         //將陣列元素從1到n-1中最大的那一個和陣列元素第n-1個
        {                                                             做交換
            list[currentMaxIndex]=list[i];
            list[i]=currentMax;
        }
    }
    for(k=0;k<n;k++)
    {
        cout<<list[k]<< " ";
    }
}
 
但是,老師上課不會寫那麼多啦~~
也是可以走捷徑地~~~
#include <algorithm>這工具是幫你把陣列裏頭得東西排好大小,排成由小到大,超好用唷~~
就這樣用sort(array_begin,array_end)   array_end =要看成array_begin+總個數
 
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int good[]={2,5,6,7,3,8,9,13,11,20,18,16,19};   //有13個=sizeof_end
    int good_end = sizeof(good)/sizeof(int);  //是以整數陣列所佔的記憶體空間除以整數陣列中的一個
    sort(good,good+good_end);                      註標所佔的記憶體空間來求得該整數陣列的長度=陣列
    for(int i=0;i<good_end;i++)                        個數。
        cout << good[i] << " ";
    cout << endl;
}
如果是由大排到小哩?
那就用reverse反轉,用法和sort差不多~~
 
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int good[]={2,5,6,7,3,8,9,13,11,20,18,16,19};
    int good_end = sizeof(good)/sizeof(int);
    sort(good,good+good_end);
    reverse(good,good+good_end);            //排完後反轉
    for(int i=0;i<good_end;i++)
        cout << good[i] << " ";
    cout << endl;
}
這就是排序啦~~希望大家喜歡~~下回見!!
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 佑佑 的頭像
    佑佑

    佑佑的語言

    佑佑 發表在 痞客邦 留言(0) 人氣()