《太閣立志傳5DX》1560年名刀村雨獲取教程 村雨怎麼獲得
阿新 • • 發佈:2022-06-03
常見排序演算法
選擇排序
void selectSort(vector<int>& array) { size_t length = array.size(); int i, j; int min; int t; for (i = 0; i < length; i++) { min = i; for (j = i + 1; j < length; j++) { if (array[j] < array[min]) min = j; } if (min != i) { t = array[min]; array[min] = array[i]; array[i] = t; } } }
插入排序
void insertSort(vector<int>& array) { size_t length = array.size(); for (int i = 1; i < length; i++) { if (array[i - 1] > array[i]) { int tmp = array[i]; int j = i - 1; while (j >= 0 && array[j] > tmp) { array[j + 1] = array[j]; j -= 1; } array[j + 1] = tmp; } } }
希爾排序
void shellSort(vector<int>& array) { size_t length = array.size(); for (int step = length / 2; step > 0; step /= 2) { for (int i = step; i < length; i++) { if (array[i - step] > array[i]) { int tmp = array[i]; int j = i - step; while (j >= 0 && array[j] > tmp) { array[j + step] = array[j]; j -= step; } array[j + step] = tmp; } } } }
歸併排序
void mergeSort(vector<int> &array, const int &start, const int &end, vector<int> &tmp)
{
if (start >= end)
return;
int mid = start + (end - start + 1) / 2;
mergeSort(array, start, mid - 1, tmp);
mergeSort(array, mid, end, tmp);
int p1 = start;
int p2 = mid;
int pos = start;
while (p1 < mid || p2 <= end)
{
if (p1 == mid)
{
while (p2 <= end)
tmp[pos++] = array[p2++];
}
else if (p2 > end)
{
while (p1 < mid)
tmp[pos++] = array[p1++];
}
else
{
if (array[p1] < array[p2])
tmp[pos++] = array[p1++];
else
tmp[pos++] = array[p2++];
}
}
for (int i = start; i <= end; i++)
array[i] = tmp[i];
}
快速排序
inline void quickSort(vector<int>& array, const int &left, const int & right)
{
if (left >= right)
return;
int tmp = array[left];
int p1 = left;
int p2 = right;
while (p1 != p2)
{
while (array[p2] >= tmp && p1 < p2)
--p2;
while (array[p1] <= tmp && p1 < p2)
++p1;
if (p1 < p2)
{
int t = array[p1];
array[p1] = array[p2];
array[p2] = t;
}
}
array[left] = array[p1];
array[p1] = tmp;
quickSort(array, left, p1 - 1);
quickSort(array, p1 + 1, right);
}