主函数体
#include<iostream>
using namespace std;
#define N 100
typedef int ElemType;
void swap(ElemType&, ElemType&);
void Bubble_Sort(ElemType*, int);
void Insertion_Sort(ElemType*, int);
void Selection_Sort(ElemType*, int);
int main() {
ElemType a[N] = { 25, 95, 83, 12, 63, 34, 32, 48, 1, 21, 29, 45, 39, 13, 35, 52, 87, 17, 78, 12, 77, 13, 85, 38, 10, 52, 33, 74, 2, 57, 6, 7, 77, 98, 55, 94, 32, 42, 51, 14, 42, 83, 74, 94, 16, 40, 9, 24, 33, 72, 91, 55, 12, 54, 4, 81, 100, 64, 68, 77, 90, 31, 11, 6, 63, 5, 52, 29, 21, 96, 33, 86, 28, 79, 19, 95, 10, 24, 53, 90, 38, 69, 19, 6, 11, 71, 24, 22, 63, 47, 20, 99, 51, 93, 36, 85, 66, 86, 33, 65 };
for (int i = 0; i < N; i++)
cout << a[i] << ' ';
return 0;
}
冒泡排序
void Bubble_Sort(ElemType a[], int n) {
int flag = 0;
for (int i = n-1; i >=0 ; i--)
{
for (int j = 0; j < i; j++)
{
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
flag = 1;
}
}
if (flag == 0) break;
}
}
void swap(ElemType &x, ElemType &y) {
ElemType t;
t = x; x = y; y = t;
}
插入排序
void Insertion_Sort(ElemType a[], int n) {
int i, j;
ElemType tmp;
for (i = 1; i < n; i++)
{
tmp = a[i];
for (j = i; j > 0; j--)
{
if (a[j - 1] <= tmp) break;
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
选择排序
void Selection_Sort(ElemType a[], int n) {
int minloc;
for (int i = 0; i < n ; i++)
{
minloc = i;
for (int j = i+1; j < n; j++)
if (a[minloc] > a[j]) minloc = j;
swap(a[i], a[minloc]);
}
}
快速排序
int Partion(ElemType a[], int low, int high) {
int pivot = a[high];
int left, right;
left = low;
right = high - 1;
while (left<right)
{
while (a[left] < pivot) left++;
while (a[right] > pivot) right--;
if (left < right) swap(a[left], a[right]);
}
swap(a[left], a[high]);
return left;
}
void Quick_Sort(ElemType a[], int low, int high) {
int p_pivot;
if (low < high) {
p_pivot = Partion(a, low, high);
Quick_Sort(a, low, p_pivot - 1);
Quick_Sort(a, p_pivot + 1, high);
}
}