数据结构 | 交换排序

交换排序包括冒泡排序、快速排序。算法复杂度以及稳定性如下:

一、冒泡排序

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值