選擇排序的兩種實現方式(C語言)

int main(void){
    
    
    int a[] = {10,7,3,46,32,21,8};
    int len = sizeof(a) / sizeof(a[0]);
    printf("排序前:");
    for (int i = 0; i < len; i++) {
        printf("%d ",a[i]);
    }
    printf("\n");
   
    /*
             第一次
        a[0] 與 a[6] 比較
        a[0] 與 a[5] 比較
        a[0] 與 a[4] 比較
        a[0] 與 a[3] 比較
        a[0] 與 a[2] 比較
        a[0] 與 a[1] 比較

             第二次
        a[1] 與 a[5] 比較
        a[1] 與 a[4] 比較
        a[1] 與 a[3] 比較
        a[1] 與 a[2] 比較
        a[1] 與 a[1] 比較

            第三次
        a[2] 與 a[4] 比較
        a[2] 與 a[3] 比較
        a[2] 與 a[2] 比較
        a[2] 與 a[1] 比較

            以此類推
    */
    // 選擇排序(1)
    for (int i = 0; i < len; i++) {
        for (int j = len - 1; j > i ; j--) {
            if (a[i] > a[j]) {        // 升序
                int temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    

        // 選擇排序(1)
    for (int i = 0; i < len; i++) {
         for (int j = len - 1; j > i ; j--) {
             if (a[i] < a[j]) {        // 降序
                 int temp = a[i];
                 a[i] = a[j];
                 a[j] = temp;
             }
         }
     }

    
    /*
             第一次
        a[0] 與 a[1] 比較
        a[0] 與 a[2] 比較
        a[0] 與 a[3] 比較
        a[0] 與 a[4] 比較
        a[0] 與 a[5] 比較
        a[0] 與 a[6] 比較

             第二次
        a[1] 與 a[2] 比較
        a[1] 與 a[3] 比較
        a[1] 與 a[4] 比較
        a[1] 與 a[5] 比較
        a[1] 與 a[6] 比較

            第三次
        a[2] 與 a[3] 比較
        a[2] 與 a[4] 比較
        a[2] 與 a[5] 比較
        a[2] 與 a[6] 比較

            以此類推
    */
    // 選擇排序(2)
    for (int i = 0; i < len - 1; i++) {
        for (int j = i + 1; j < len; j++) {
            if (a[i] > a[j]) {  // 升序
                int temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    
    // 選擇排序(2)
    for (int i = 0; i < len - 1; i++) {
        for (int j = i + 1; j < len; j++) {
            if (a[i] < a[j]) {  // 降序
                int temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    
    
    printf("排序後:");
    for (int i = 0 ; i < len; i++) {
        printf("%d ",a[i]);
    }
    
    printf("\n");
    getchar();
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章