1.快排
class Solution {
public:
void sortIntegers2(vector<int>& A) {
// Write your code here
if(A.empty()){
return;
}
for(int i = A.size() / 2 - 1; i >= 0; i--)
heap_adjust(A, A.size(), i);
for(int i = A.size() - 1; i >= 1; i--){
swap(A[0], A[i]);
heap_adjust(A, i, 0);
}
}
void heap_adjust(vector<int>& A, int length, int index){
int left = index * 2 + 1;
int right = left + 1;
int max_index = index;
if(left < length && A[left] > A[max_index])
max_index = left;
if(right < length && A[right] > A[max_index])
max_index = right;
if(max_index != index){
swap(A[max_index], A[index]);
heap_adjust(A, length, max_index);
}
}
};
2.归并排序
class Solution {
public:
void sortIntegers2(vector<int>& A) {
// Write your code here
if(A.empty())
return;
vector<int> temp(A.size(), 0);
mergesort(A, 0, A.size() - 1, temp);
}
void mergesort(vector<int>& A, int start, int end, vector<int>& temp){
if(start >= end)
return;
int mid = (end - start) / 2 + start;
mergesort(A, start, mid, temp);
mergesort(A, mid + 1, end, temp);
merge(A, start, end, temp);
}
void merge(vector<int>& A, int start, int end, vector<int>& temp){
int mid = (end - start) / 2 + start;
int index = start, first = start, second = mid + 1;
while(first <= mid && second <= end){
if(A[first] < A[second]){
temp[index++] = A[first++];
}
else{
temp[index++] = A[second++];
}
}
while(first <= mid)
temp[index++] = A[first++];
while(second <= end)
temp[index++] = A[second++];
for(int i = start; i <= end; i++)
A[i] = temp[i];
}
};
3.堆排序
class Solution {
public:
void sortIntegers2(vector<int>& A) {
// Write your code here
if(A.empty())
return;
quicksort(A, 0, A.size() - 1);
}
void quicksort(vector<int> &A, int start, int end){
if(start >= end)
return;
int left = start, right = end;
int mid_num = A[(right - left) / 2 + left];
while(left <= right){
while(left <= right && A[right] > mid_num)
right--;
while(left <= right && A[left] < mid_num)
left++;
if(left <= right)
swap(A[left++], A[right--]);
}
quicksort(A, start, right);
quicksort(A, left, end);
}
};