首页 > 学院 > 开发设计 > 正文

冒泡排序、插入排序、快速排序的简单实现

2019-11-08 01:14:20
字体:
来源:转载
供稿:网友
#include "stdafx.h"#include <iostream>#include <windows.h>using namespace std;//冒泡排序void BubbleSort(int *arr, int sz){	int iTemp = 0;	for (int i = 0; i < sz; i++)	{		for (int j = sz-1; j > i; j-- )		{			if (arr[j] < arr[j-1])//把相邻两个数比较,如果后面的数较小就和前面的数换位置			{				iTemp = arr[j-1];				arr[j-1] = arr[j];				arr[j] = iTemp;			}		}	}}//插入排序void SelectSort(int arr[], int sz){	int iTemp = 0;//iTemp为当前最小数	int ipos = 0;	for (int i = 0; i < sz-1; i++)	{		iTemp = arr[i];		iPos = i;		for (int j = i+1; j < sz; j++)		{			//把所有数和第一个数进行比较,如果小于第一个数就记录下来,			//直到找到最小数,然后插入到最前面,然后找第二小的数换到第二位置,以此进行			if (arr[j]<iTemp)			{				iTemp = arr[j];				iPos = j;			}		}		arr[iPos] = arr[i];		arr[i] = iTemp;	}}void swap(int *arr, int one, int two){	int iTemp = 0;	iTemp = arr[one];	arr[one] = arr[two];	arr[two] = iTemp;}//快速排序,使用一个分界值,把小于它的全部放在他前面,大于它的放在它后面//然后对前后两部分继续采取同样递归方式void QuiteSort(int *arr, int iLeft, int iRight){	if (iLeft >= iRight)	{		return;	}	int i = 0;	int iLast = 0;//用于记录最近一次值移动的下标	swap(arr, iLeft, (iLeft+iRight)/2);//选定中间位置的值作为分界值,并把他移动到首位	iLast = iLeft;	for (i = iLeft+1; i <= iRight; i++)//把所有小于分界值的数全放在分界值后面	{		if (arr[i]<arr[iLeft])		{			swap(arr, ++iLast, i);//		}	}	swap(arr, iLeft, iLast);	QuiteSort(arr, iLeft, iLast-1);//对左边部分进行排序	QuiteSort(arr, iLast+1, iRight);//对右边部分进行排序}void main(){	int arr1[16] = {1,32,11,53,2321,65, 888,12,33,124,86,9,54,21,65,37};	int arr2[16] = {1,32,11,53,2321,65, 888,12,33,124,86,9,54,21,65,37};	int arr3[16] = {1,32,11,53,2321,65, 888,12,33,124,86,9,54,21,65,37};	BubbleSort(arr1, 16);	for (int i=0; i<16;i++)	{		cout << arr1[i] << " ";	}	cout << endl;	SelectSort(arr2, 16);	for (int i=0; i<16;i++)	{		cout << arr2[i] << " ";	}	cout << endl;	QuiteSort(arr3, 0, 15);	for (int i=0; i<16;i++)	{		cout << arr3[i] << " ";	}	cout << endl;	system("pause");	return ;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表