数据结构与算法--冒泡排序算法有问题
本帖最后由 zlQhs 于 2015-3-28 14:14 编辑代码如下:#include "stdafx.h"
#include <iostream>
#define DATA_SIZE 14
void BubbleSort1(int data[], int iDataSize)
{
int iTemp = 0;
int iCompareCount = 0;
int iMoveCount = 0;
for ( int i = 0; i < iDataSize - 1; i++)
{
for ( int j = i + 1; j < iDataSize; j++)
{
iCompareCount++;
if ( data > data )
{
iMoveCount++;
iTemp = data;
data = data ;
data = iTemp;
}
}
}
printf("第一种冒泡排序:\n排序进行了%d次比较,进行了%d次移动\n", iCompareCount, iMoveCount);
}
void BubbleSort2(int data[], int iDataSize)
{
int iTemp = 0;
int iCompareCount = 0;
int iMoveCount = 0;
for ( int i = 0; i < iDataSize - 1; i++)
{
for ( int j = iDataSize - 1; j > i; j--)
{
iCompareCount++;
if ( data > data )
{
iMoveCount++;
iTemp = data;
data = data ;
data = iTemp;
}
}
}
printf("第二种冒泡排序:\n排序进行了%d次比较,进行了%d次移动\n", iCompareCount, iMoveCount);
}
void BubbleSort3(int data[], int iDataSize)
{
int iTemp = 0;
int iCompareCount = 0;
int iMoveCount = 0;
bool bFlag = true;
for ( int i = 0; i < iDataSize - 1 && bFlag; i++)
{
for ( int j = iDataSize - 1; j > i; j--)
{
iCompareCount++;
bFlag = false;
if ( data > data )
{
iMoveCount++;
iTemp = data;
data = data ;
data = iTemp;
bFlag = true;
}
}
}
printf("第三种冒泡排序:\n排序进行了%d次比较,进行了%d次移动\n", iCompareCount, iMoveCount);
}
void printResult(int data[], int iDataSize)
{
printf("排序后的结果是:");
for ( int i = 0; i < iDataSize; i++)
{
printf("%d ", data);
}
printf("\n\n");
}
void sort1()
{
int data = {3,6,1,4,2,5,9,33,8,1,22,32,11,18};
BubbleSort1(data, DATA_SIZE);
printResult(data, DATA_SIZE);
}
void sort2()
{
int data = {3,6,1,4,2,5,9,33,8,1,22,32,11,18};
BubbleSort2(data, DATA_SIZE);
printResult(data, DATA_SIZE);
}
void sort3()
{
int data = {3,6,1,4,2,5,9,33,8,1,22,32,11,18};
BubbleSort3(data, DATA_SIZE);
printResult(data, DATA_SIZE);
}
int _tmain(int argc, _TCHAR* argv[])
{
sort1();
sort2();
sort3();
getchar();
return 0;
}
运行结果如下:
老师 当数组是int[] a = new int[]{0,1,30,14,5,6,7,81,9,2222};第三种冒充排序是错的吧。
页:
[1]