排序算法复杂度及代码

//排序算法,从小到大
#include <iostream>
using namespace std;
void swap(int &a, int &b)
{
	int temp;
	temp = a;
	a = b;
	b = temp;
}

//选择排序
void selectSort(int array[],int len)
{
	cout << "selectSort:";
	for (int i = 0; i < len; i++)
	{
		for (int j = i+1; j < len; j++)
		{
			if (array[i]>array[j])
			{
				swap(array[i], array[j]);
			}
		}
		cout << array[i] << " ";
	}
	cout << endl;
}

//冒泡排序
void bubbleSort(int array[], int len)
{
	cout <<"bubbleSort:";
	for (int i = 0; i < len; i++)
	{
		for (int j =len-1; j >i; j--)
		{
			if (array[i]>array[j])
			{
				swap(array[i], array[j]);
			}
		}
		cout << array[i] << " ";
	}
	cout << endl;
}
//插入排序
void insertSort(int array[], int len)
{
	cout << "insertSort:";
	int i = 0;
	for (i = 0; i < len; i++)
	{
		int k = i;
		int temp = array[k];
		for (int j = k; j >=0; j--)
		{
			if (temp<array[j])
			{
				array[j+1]=array[j];
				k = j;
			}
		}
		array[k] = temp;
		cout << array[i] << " ";
	}
	cout << endl;
}

//希尔排序
void shellSort(int array[], int len)
{
	cout << "shellSort:";
	int i = 0;
	int gap = len;
	for (i = gap; i < len&&gap>=1; i+=gap)
	{
		gap = gap / 3 + 1;
		int k = i;
		int temp = array[k];
		for (int j = i-gap; j >= 0; j -= gap)
		{
			if (temp<array[j])
			{
				array[j + gap] = array[j];
				k = j;
			}
		}
		array[k] = temp;
	}
	for (int i = 0; i < len; i++)
	{
		cout << array[i] << " ";
	}
	cout << endl;
}

//快速排序
int partition(int array[], int low, int high)
{
	int pivot = array[low];
	if (low < high)
	{
		while ((low < high) && (array[high] >= pivot))
		{
			high--;
		}
		swap(low,high);
		while ((low < high) && (array[low] <pivot))
		{
			low++;
		}
		swap(low, high);
	}
	return low;
}
void quickSort(int array[], int low, int high)
{
	if (low < high)
	{
		int pivot = partition(array, low, high);
		partition(array, low, pivot - 1);
		partition(array, pivot + 1, high);
	}
}
void quickSort(int array[], int len)
{
	quickSort(array, 0,len-1);
	cout << "quickSort:";
	for (int i = 0; i < len; i++)
	{
		cout << array[i] << " ";
	}
	cout << endl;
}

int main()
{
	int array[] = {8,7,55,69,2,58,4,37,46,24};
	int len = 10;
	cout << "原序列:";
	for (int i = 0; i < len; i++)
	{
		cout << array[i] << " ";
	}
	cout << endl;

	selectSort(array, len);
	bubbleSort(array, len);
	insertSort(array, len);
	shellSort(array, len);
	quickSort(array, len);

	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值