# 排序不簡單 https://neoj.sprout.tw/problem/465/ ### Problem Description 如題啦,排序原本很簡單的,但是加入指標 Pointer 之後就不簡單了QAQ 請實作排序整數陣列的函示 EzSort。 ### Sample Code ```cpp #include <iostream> ​ void EzSort(int N, int const **ptr_array); ​ int main() { int N, arr[1000], *ptr[1000]; std::cin >> N; for (int i = 0; i < N; i++) { std::cin >> arr[i]; ptr[i] = &(arr[i]); } EzSort(N, (int const **)ptr); for (int i = 0; i < N; i++) { std::cout << *(ptr[i]) << (i == N - 1 ? '\n' : ' '); } } ​ /* Your code will be placed here */ ``` ### Objective 實作 ```cpp EzSort(int N, int const **ptr_array); ``` 該函式將一個 const int 的指標陣列依照指標的內容(取值)將這些指標排序。 ### More Detailed + Main 中的 `ptr` 陣列是為了紀錄那 $N$ 個整數的指標;在這裡用 `arr` 作為儲存該 $N$ 個整數是因為我們還沒教到 new/delete 的概念,敬請期待下週課程。 + EzSort 中的 `ptr_array` 的型態是 int const **,根據 [1],我們可以將他看成 “Pointer to (pointer to const int)”,我們來逐一解釋: + **const** [2]:我們不會詳細介紹到,但 const 的概念就是該變數是「唯讀」的概念,只能讀該數值但不能修改。使用原因是因為怕你們誤解題目而更改指標的內容,所以在此用 const。如果還是不懂就假抓沒有看到 const 吧 xDDD + 括號內的東西:根據樓上的粗略解釋,我們可以把括號內的東西視為 “pointer to int”,這就是一個指到整數的指標(int*) + 括號外的大寫 Pointer:這邊的 Pointer 是為了指示 ptr_array 是一個 “pointer to (const) int” 的陣列的指標。 ### Input Format 輸入的第一行有一個整數 $N$。接下來一行有 $N$個數字,分別代表 $a_i$。 $1≤N≤1000$ $0≤a_i<10^9+7,\ \ 0≤i<N$ ### Output Format 請將 N 個排序好的數字於一行,行尾請記得沒有多餘空白且要換行。 ### Hint 本題 $N$ 至多到 1000,使用 [第十週](https://tw-csie-sprout.github.io/c2019/#!slides.md#%E7%AC%AC%E5%8D%81%E9%80%B1%E6%8A%95%E5%BD%B1%E7%89%87_5/11) 的任何 $O(N^2)$ 之排序演算法都是可以的! ### Reference 1. [Judgegirl - 100](https://judgegirl.csie.org/problem/0/100):自從寫到該題查看連結[stackoverflow - What is the difference between …](https://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const) 後便覺得受用無窮,決定於此分享給大家。 1. [Microsoft - const](https://docs.microsoft.com/zh-tw/cpp/cpp/const-cpp?view=vs-2019) # Code ```cpp #include <algorithm> int to_test[1]; int* a = &to_test[0]; void EzSort(int N, int const **ptr_array) { int st = *ptr_array - a; for(int i = 0; i < N - 1; i++) { int min = i; for(int j = i + 1; j < N; j++) { if(*ptr_array[j] < *ptr_array[min]) min = j; } std::swap(ptr_array[i], ptr_array[min]); //std::swap(to_test[st + i], to_test[st + min]); } } ```