题目描述:
Given an integer array, sort it in ascending order. Use selection sort, bubble sort, insertion sort or any O(n2) algorithm.
Example
题目思路:
Given [3, 2, 1, 4, 5]
, return [1, 2, 3, 4, 5]
.
O(n^2)代价的sort方法有很多,随便想了一种:对于每一个A[i],从j = i + 1...开始寻找比它更小的数,如果找到了就swap i and j,这样保证i永远是i...A.size() - 1中最小的数。
Mycode(AC = 50ms):
class Solution {
public:
/**
* @param A an integer array
* @return void
*/
void sortIntegers(vector<int>& A) {
// Write your code here
for (int i = 0; i < A.size(); i++) {
for (int j = i + 1; j < A.size(); j++) {
if (A[i] > A[j]) {
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
}
}
};