冒泡排序

#includeusing namespace std;/*
	完成冒泡排序
	输入参数:r为一维数组,n为数组长度
	返回值:void
*/void BubbleSort(int *r, int n){
	bool change = true;
	int temp;
	for(int i=0; i<n&&change; i++){
		change = false;
		for(int j=0; j<n-i; j++){
			if(r[j]>r[j+1]){//升序排序
				temp = r[j];
				r[j] = r[j+1];
				r[j+1] = temp;
				change = true;
			}
		}
	}}int main(int argc, char const *argv[]){
	int arr[]={1,3,8,5,9,7};
	for(auto e:arr)cout<<e<<" ";
	cout<<endl;
	BubbleSort(arr, 6);
	for(auto e:arr)cout<<e<<" ";
	cout<<endl;
	return 0;}

数据结构   常用排序算法的想法_数据结构

希尔排序

#includeusing namespace std;/*
	完成希尔排序
	输入参数:r为一维数组,length为数组r的长度
	返回值:void
*/void ShellSort(int *r, int length){
	if (r == NULL || length <= 0)
        return;
    int increment = length;
    while (increment > 1)
    {
        increment = increment / 3 + 1;
        for (int i = increment; i < length; i++)
        {
            int temp = r[i];
            if (r[i] < r[i - increment]){
                int j;
                for (j = i - increment; j >= 0 && r[j] > temp; j = j - increment)
                    r[j + increment] = r[j];
                r[j + increment] = temp;
            }
        }
    }}int main(int argc, char const *argv[]){
	int arr[]={1,3,8,9,5,7,6}, len = 7;
	for(auto e:arr)cout<<e<<" ";
	cout<<endl;

	ShellSort(arr, len);
		
	for(auto e:arr)cout<<e<<" ";
	cout<<endl;
	return 0;}

数据结构   常用排序算法的想法_数据结构_02

快速排序

#include#include#define N 7using namespace std;int QKPass(int *r, int low, int high){
	int x = r[low]; //选择基准记录
	while(low<high){
		while(low<high && r[high]>=x)high--; //从右往左找小于x的记录

		if(low<high){	//找小于x的记录送入空单元r[low]
			r[low] = r[high];
			low++;
		}

		while(low<high && r[high]<x)low++;

		if(low<high){ //找大于x的记录送入空单元r[high]
			r[low] = r[high];
			high--;
		}
	}
	r[low] = x;
	return low;}/*
	完成快速排序
	输入参数:r为一维数组,low为r数组第一个元素下标(正常是0),high是r数组最后一个元素下标
	返回值:void
*/// int ss=0;void QKSort(int *r, int low, int high){//排序的数组过大过长,堆栈溢出(是用到了递归的缘故)
	if(low<high){
		int pos = QKPass(r, low, high);
		QKSort(r, low, pos-1);
		QKSort(r, pos+1, high);
	}
	// cout<<"ss = "<<ss++<<endl;}int main(int argc, char const *argv[]){
	int arr[]={1,3,8,9,5,7,6}, len = 7;
	for(auto e:arr)cout<<e<<" ";
	cout<<endl;
	QKSort(arr, 0, N-1);
	for(auto e:arr)cout<<e<<" ";
	cout<<endl;
	QKSort(arr, 0, N-1);
	for(auto e:arr)cout<<e<<" ";
	cout<<endl;
	QKSort(arr, 0, N-1);
	for(auto e:arr)cout<<e<<" ";
	cout<<endl;
	return 0;}

数据结构   常用排序算法的想法_数据结构_03

简单的选择排序

#includeusing namespace std;/*
	完成选择排序
	输入参数:r为一维数组,n为数组长度
	返回值:void
*/void SelecSort(int *r, int n){
	int temp, k;
	for(int i=0; i<n; i++){
		k = i;
		for(int j=i+1; j<n; j++){
			if(r[j]<r[k])k=j;
		}
		if(k!=i){
			temp = r[i];
			r[i] = r[k];
			r[k] = temp;
		}
	}}int main(int argc, char const *argv[]){
	int arr[]={1,3,8,5,9,7};
	for(auto e:arr)cout<<e<<" ";
	cout<<endl;

	SelecSort(arr, 6);
		
	for(auto e:arr)cout<<e<<" ";
	cout<<endl;
	return 0;}

数据结构   常用排序算法的想法_数据结构_02