2019年3月5日 星期二

【演算法】

【演算法】
用一種簡單的程式碼,去排序法
兩個兩個相比,相當機械化,當數量愈多時,執行時間會愈久



因為必定要比較當緣故,例如假如有

10 個數字要比較就要執行
9+8+7+6+5+4+3+2+1次 = 45次

  5 個數字
4+3+2+1次=10次

以此類推



#include <iostream>
#include <string.h>
#include <stdlib.h> /* 亂數相關函數 */
#include <time.h>   /* 時間相關函數 */
#include <windows.h>

using namespace std;

/* 輸入任意字串, 進行反向輸出.  */
void S0606(void) {

int array[10];
int len = sizeof(array) / sizeof(int);
int temp;



/* 設定亂數種子 */
srand(time(NULL));

/* 給陣列賦予值 */
for(int i = 0; i<len; i++)
{
array[i] = rand()%100;
}

/* 查看排序前陣列的順序 */
cout << "排序前:";
for(int i= 0; i<len; i++)
{
cout << array[i] << " ";
}
cout << endl;

/* 開始執行排序法 */
for(int j = 0; j < len - 1; j++) // 最外層的for迴圈為主體
{
for(int i = j + 1; i < len; i++) // 最內層的for迴圈為 要和主體比較的次等
{
for(int k = 0; k < len; k++) // 顯示當前狀態時的順序
{
if(k == i) cout << "(" ; // 只有其中一個條件達成 即給予 " [ "
if(k == j) cout << "[" ; // 只有其中一個條件達成 即給予 " [ "
cout << array[k];
if(k == i) cout << ")" ; // 只有其中一個條件達成 即給予 " ] "
if(k == j) cout << "]" ; // 只有其中一個條件達成 即給予 " ] "
cout << " " ;
}

if(array[j] >= array[i]) // 進行兩數之間的比較
{
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
cout << endl; // 換行
Sleep(1000);  // delay函數
}
cout << endl ;
}

/* 查看排序後陣列的順序 */
cout << "排序後:";
for(int i= 0; i<len; i++)
{
cout << array[i] << " ";
}
cout << endl;
}

顯示結果如下圖所示:

沒有留言:

張貼留言

Android Studio IDE 錯誤

 :app:compile xxxxx JavaWithJavac FAILED An exception has occurred in the compiler (1.8.0_312). Please file a bug against the Java compiler ...