数据结构实战

    返回首页    发表留言
本文作者:李德强
          第三节 冒泡排序
 
 

        冒泡排序的原理很简单,即:依次将相邻的两个关键字比较,如果k[i] > k[i + 1]则将两个元素的位置交换,第一趟结束找出最大的元素并将其移动到末尾位置;第二趟则在前size - 1个元素中找到最大的元素,并将其移动到倒数第2个位置上;以此类推……

#include <stdio.h>

#define SIZE	(10)

//冒泡排序
void bubble_sort(int array[], int size)
{
	for (int i = 0; i < size - 1; i++)
	{
		for (int j = 0; j < size - i - 1; j++)
		{
			//将较大的值向右交换
			if (array[j] > array[j + 1])
			{
				int t = array[j];
				array[j] = array[j + 1];
				array[j + 1] = t;
			}
		}
	}
}

//冒泡排序
void bubble_sort2(int array[], int size)
{
	for (int i = 0; i < size; i++)
	{
		int ind = -1;
		int t = -1;
		for (int j = 0; j < size - i; j++)
		{
			//找到本趟的最大值
			if (array[j] > t)
			{
				t = array[j];
				//记录最大值的位置
				ind = j;
			}
		}
		//交换最大值的位置
		t = array[size - i - 1];
		array[size - i - 1] = array[ind];
		array[ind] = t;
	}
}

//显示数组
void display(int *array, int size)
{
	for (int i = 0; i < size; i++)
	{
		printf("%d ", array[i]);
	}
	printf("\n");
}

int main(int argc, char **args)
{
	int array[SIZE] =
	{ 9, 3, 1, 2, 5, 8, 7, 0, 6, 4 };
	display(array, SIZE);
	bubble_sort2(array, SIZE);
	display(array, SIZE);

	int array2[SIZE] =
	{ 9, 3, 1, 2, 5, 8, 7, 0, 6, 4 };
	display(array2, SIZE);
	bubble_sort2(array2, SIZE);
	display(array2, SIZE);

	return 0;
}

        运行结果:

9 3 1 2 5 8 7 0 6 4 
0 1 2 3 4 5 6 7 8 9 
9 3 1 2 5 8 7 0 6 4 
0 1 2 3 4 5 6 7 8 9 

        本例代码:

code path   chapter.08/e.g.8.3/

https       https://github.com/magicworldos/datastructure.git
git         git@github.com:magicworldos/datastructure.git
subverion   https://github.com/magicworldos/datastructure

    返回首页    返回顶部
  看不清?点击刷新

 

  Copyright © 2015-2023 问渠网 辽ICP备15013245号