交换排序包括冒泡排序、快速排序。算法复杂度以及稳定性如下:
一、冒泡排序
#include <stdio.h>
typedef int ElemType;
/* 交换函数 */
void sawp(ElemType* a, ElemType* b) {
ElemType temp;
temp = *a;
*a = *b;
*b = temp;
}
/* 冒泡排序 */
void BubbleSort(ElemType a[], int n) {
for (int i = 0; i < n - 1; i++) {
int flag = 0;
for (int j = n - 1; j > i; j--) {
if (a[j - 1] > a[j]) {
sawp(&a[j - 1], &a[j]);
flag = 1;
}
}
if (flag == 0)
return;
}
}
/* 打印结果 */
void SortPrint(ElemType* a, int len) {
printf("冒泡排序: ");
for (int i = 0; i < len; i++)
printf("%d ", a[i]);
}
int main() {
ElemType a[] = { 12,3,22,1,15,32,88,7,9 };
int len = sizeof(a) / sizeof(a[0]);
BubbleSort(a, len);
SortPrint(a, len);
}
二、快速排序
#include<stdio.h>
typedef int ElemType;
/* 划分操作 */
int Partition(ElemType A[], int low, int high) {
ElemType 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(ElemType* a, int low, int high) {
if (low < high) {
int pivotops = Partition(a, low, high);
QuickSort(a, low, pivotops - 1);
QuickSort(a, pivotops + 1, high);
}
}
/* 打印结果 */
void SortPrint(ElemType* a, int len) {
printf("快速排序:");
for (int i = 0; i < len; i++)
printf("%d ", a[i]);
}
int main() {
ElemType a[] = { 12,3,22,4,44,44,1,5,32,88,7,9 };
int len = sizeof(a) / sizeof(a[0]);
QuickSort(a, 0, len - 1);
SortPrint(a, len);
return 0;
}