#include<iostream>
using namespace std;
//冒泡排序
void Bubblesort(int a[], int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
//快速排序
int Partition(int a[], int low, int high) //初始传入low=0,high=len-1
{
int pivot = a[low];
while (low < high)
{
while (low < high && a[high] >= pivot)
--high;
a[low] = a[high];
while (low < high && a[low] <= pivot)
++low;
a[high] = a[low];
}
a[low] = pivot;
return low;
}
void Quicksort(int a[], int low, int high)
{
if (low < high)
{
int pivotpos = Partition(a, low, high);
Quicksort(a, low, pivotpos - 1);
Quicksort(a, pivotpos + 1, high);
}
}
//直接插入排序
void Insertsort(int a[], int n)
{
for (int i = 1; i < n; i++)
{
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
//选择排序
void Selectsort(int a[], int n)
{
int min, i, j;
for (i = 0; i < n - 1; i++)
{
min = i;
for (j = i + 1; j < n; j++)
{
if (a[j] < a[min])
min = j;
}
if (min != i)
{
int temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
}
int main()
{
int a[] = { 9,8,6,7,4,2,3 };
int n = 7;
Bubblesort(a, n);
Quicksort(a, 0, 6);
Insertsort(a, 7);
Selectsort(a, n);
cout << "排序后的数组:" << endl;
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}
冒泡、快速、直接插入、选择排序(c++)
于 2022-03-25 11:10:19 首次发布