2019年3月7日 星期四

【演算法】 (優化、指標)

將原本的程式改成用指標來做
另外建構幾個副函數去調用功能,減少重複性的程式碼



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

#define Max 5

using namespace std;

int *sortArray(int *array);
void showArray2(int *array);



int *sortArray(int *array)
{
int temp;
for(int i = 0 ; i < Max - 1; i++)
{
for(int j = i + 1 ; j < Max; j++)//1,4
{
if(*(array + i ) >= *(array + j ))
{

         temp = *(array + i );
*(array + i ) = *(array + j );
*(array + j ) = temp;
}
}
}

return array;
}

void showArray2(int *array)
{
for(int i = 0; i < Max; i++)
{
cout << *(array+i) << '\0';
}
cout << endl ;
}

void S0706(void) {

int number[Max];

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

/* 給陣列賦予值 */
for(int i = 0; i < Max; i++)
number[i] = rand()%100;


cout << "排序前:" << endl;
showArray2(number);

*sortArray(number);

cout << "排序後:" << endl;
showArray2(number);
}
結果如下圖所示:

沒有留言:

張貼留言

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 ...