void bunSort(int arr[], int length)
{
while (length--)
{
for (int i = 0; i < length; i++)
{
if (arr[i + 1] < arr[i]) {
int temp = arr[i+1];
arr[i + 1] = arr[i];
arr[i] = temp;
}
}
}
}
冒泡排序:从前往后一直比较两个元素大小并交换
void selectSort(int arr[], int length)
{
for (int i = 0; i < length; i++)
{
int k = i;
for (int j = i + 1; j < length; j++) {
if (arr[j] < arr[k]) {
k = j;
}
}
int temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
}
选择排序:直接按大小选择出最小的往前放
void insertSort(int arr[], int length)
{
int count = 0;
for (int i = 1; i < length; i++)
{
for (int j = i; j >= 1 && arr[j] < arr[j - 1]; j--)
{
count++;
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
插入排序:可以理解为选小的一直往前插入
void shellSort(int arr[], int length)
{
int h = 4;//间隔为4
while (h >= 1)
{
for (int i = h; i < length; i++)
{
for (int j = i; j >= h && arr[j] < arr[j - h]; j--)
{
int temp = arr[j];
arr[j] = arr[j - h];
arr[j - h] = temp;
}
}
h /= 2;
}
}
希尔排序:对数组进行多次插入排序
void quickSort(int arr[], int left, int right)
{
if (left >= right)
return;
int i = left;
int j = right;
int pivot = arr[i];
while (i < j)
{
while (i < j && arr[j] >= pivot)
j--;
arr[i] = arr[j];
while (i < j && arr[i] <= pivot)
i++;
arr[j] = arr[i];
}
arr[i] = pivot;
quickSort(arr, left, i - 1);
quickSort(arr, i + 1, right);
}
快速排序:先以第一个为标记。然后左j找大,右i找小,找到交换,直到i、j大小相反,再以i数拿出去为标记,原标记交换进来,重新开始循环
int temp[N];
void countSort(int arr[], int length)
{
for (int i = 0; i < length; i++) {
temp[arr[i]]++;
}
for (int i = 0, j = 0; i < N; i++) {
while (temp[i]--)
{
arr[j++] = i;
}
}
}
计数排序:值当下标,直接用下标顺序排序
void redixSort(int arr[], int length)
{
int i;
int j;
int ii;
int jj;
int temp[10][10];
for (ii = 0; ii < 10; ii++)
for (jj = 0; jj < 10; jj++)
temp[ii][jj] = -1;
for (int k = 10; k < 10000; k *= 10) {
for (i = 0; i < length; i++) {
int index = (arr[i] % k) / (k / 10);
j = 0;
while (temp[index][j] != -1)
j++;
temp[index][j] = arr[i];
}
i = 0;
for (ii = 0; ii < 10; ii++) {
for (jj = 0; jj < length && temp[ii][jj] != -1; jj++) {
arr[i++] = temp[ii][jj];
temp[ii][jj] = -1;
}
}
}
}
基数排序:从个数位开始,放进0-9下标,再拿出来,再放进去,再重复十位、百位