您的位置:首页 > 编程语言 > C语言/C++

冒泡排序

2016-03-22 01:02 369 查看
冒泡排序描述

       冒泡排序比较表中的相邻元素,如果它们是逆序的话就交换它们的位置。重复多次以后,最终,最大元素就“沉到”了列表的最后一个位置。第二遍操作将第二大的元素沉下去。这样一直做,知道n-1遍以后,该列表修排好序了。第 i 遍(0<= i <=n-2)遍冒泡排序可以用下面的示意图来表示:

                                                        


       算法:

BubbleSort(A[0...n-1])
//该算法用冒泡排序对给定的数组排序
//输入:一个可排序的数组A[0...n-1]
//输出:非降序排列的数组A[0...n-1]
for i <- 0 to i <- n-2 do
for j <- 0 to j <- n-2-i do
if A[j] > A[j+1]  swap A[j] and A[j+1</strong>


冒泡排序的实现

// BubbleSort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "typedef.h"

/*
*函数名:Compare_uint
*参数:pKey1  指向第一个比较元素的地址
*      pKey2  指向第二个比较元素的地址
*功能:比较两个元素的大小
*返回值:1 表示Key1 大于 Key2
*        -1 表示Key1 小于 Key2
*        0 表示Key1 等于 Key2
*作者:AlbertoNo1
*日期:2016-03-15
*/
INT32 Compare_uint(VOID *pKey1, VOID *pKey2)
{
/*对两个无符号整型数进行比较*/
if (*((UINT32*)pKey1) > *((UINT32*)pKey2))
{
return 1;
}
else if (*((UINT32*)pKey1) < *((UINT32*)pKey2))
{
return -1;
}
else
{
return 0;
}
}

/*
*函数名:Swap
*参数:pKey1  指向第一个交换元素的地址
*      pKey2  指向第二个交换元素的地址
*      uiKeySize 交换元素所占内存大小(Byte)
*功能:交换两个元素的位置
*返回值:无
*作者:AlbertoNo1
*日期:2016-03-15
*/
VOID Swap(VOID *pKey1, VOID *pKey2, UINT32 uiKeySize)
{
VOID *pTemp = NULL;

if (NULL == (pTemp = malloc(uiKeySize)))
{
return;
}

memcpy(pTemp, pKey1, uiKeySize);
memcpy(pKey1, pKey2, uiKeySize);
memcpy(pKey2, pTemp, uiKeySize);
}

/*
*函数名:BubbleSort
*参数:pData  待排序数组数据的首地址
*      uiSize 数据的元素个数
*      uiElmSize  数据元素所占内存大小(Byte)
*      compare  两个元素的比较函数
*功能:对数组进行冒泡排序
*返回值:无
*作者:AlbertoNo1
*日期:2016-03-21
*/
VOID BubbleSort(VOID *pData, UINT32 uiSize, UINT32 uiElmSize, INT32 (*compare)(VOID *pKey1, VOID *pKey2))
{
UINT32 i = 0;
UINT32 j = 0;
UINT32 uiSwitchPos = 0;  /*存储一轮比较最终要交换的位置*/

CHAR *pucData = NULL;

if (uiSize <= 1)
{/*不用排序*/
return ;
}

pucData = (CHAR*)pData;

for (i = 0; i < uiSize -1; i++)
{/*进过 uiSzie-1 轮比较后,排序完成*/

for (j = 0; j < (uiSize-1)-i; j++)
{
if (compare(&pucData[j*uiElmSize], &pucData[(j+1)*uiElmSize])>0)
{
Swap(&pucData[j*uiElmSize], &pucData[(j+1)*uiElmSize], uiElmSize);
}
}
}

return ;
}

int _tmain(int argc, _TCHAR* argv[])
{
INT32 iRet = 0;
UINT32 uiLoop = 0;

//UINT32 auiData[] = {10,15,15,18,20,20,20,36,48,51,51,77,77};
//UINT32 auiData[] = {77,77,51,51,48,36,20,20,20,18,15,15,10};
UINT32 auiData[] = {77,15,20,18,51,51,36,10,77,15,20,20,48};
//UINT32 auiData[] = {77,77};
//UINT32 auiData[] = {77};

BubbleSort(auiData, sizeof(auiData)/sizeof(auiData[0]), sizeof(auiData[0]),Compare_uint);

printf("Bubble Sort Success.\n");
printf("Result:\n");

for (uiLoop = 0; uiLoop < sizeof(auiData)/sizeof(auiData[0]); uiLoop++)
{
printf("%d  ", auiData[uiLoop]);
}

getchar();
return 0;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息