基础算法

冒泡排序

#include<stdio.h>
#define MAX 50
typedef int KeyType;
typedef char InfoType;
typedef struct
{
	KeyType key;
	InfoType otheritems;
}RecType;
typedef RecType SeqRecList[MAX];
void BubbleSort_up(SeqRecList R,int n)
{
	int i,j;
	int flag=1;
	RecType temp;
	for(i=1;i<=n&&1==flag;i++)
	{
		flag=0;
		for(j=n-1;j>=i;j--)
		{
			if(R[j+1].key<R[j].key)
			{
				temp=R[j+1];
				R[j+1]=R[j];
				R[j]=temp;
				flag=1;
			}
		}
	}
}
int main()
{
	int i;
	SeqRecList q;
	for(i=0;i<MAX;i++)
	{
		q[i].key=MAX-i;
		q[i].otheritems='b'+i;
	}
//	BubbleSort_up(q,MAX-1);
	for(i=0;i<MAX;i++)
	{
		printf("%d\n",q[i].key);
	}
	printf("hello\n");
	return 0;
}
可以运行的冒泡排序,呵呵,自己照书上写的哦


下面把向下沉冒泡排序代码贴下

void BubbleSort_Down(SeqRecList R,int n)
{
	int i,j;
	int flag=1;
	RecType temp;
	for(i=n;i>=1&&1==flag;i--)
	{
		flag=0;
		for(j=1;j<=i-1;j++)
		{
			if(R[j+1].key<R[j].key)
			{
				temp=R[j+1];
				R[j+1]=R[j];
				R[j]=temp;
				flag=1;
			}
		}
	}
}

快速排序算法如下

#include<stdio.h>
#define MAX 50
typedef int KeyType;
typedef char InfoType;
typedef struct
{
	KeyType key;
	InfoType otheritems;
}RecType;
typedef RecType SeqRecList[MAX];
int Partition(SeqRecList R,int low,int high)
{
	RecType pivot;
	pivot=R[low];
	while(low<high)
	{
		while(low<high&&R[high].key>=pivot.key)
			high--;
		if(low<high)
		{
			R[low]=R[high];
			low++;
		}
		while(low<high&&R[low].key<pivot.key)
			low++;
		if(low<high)
		{
			R[high]=R[low];
			high--;
		}
	}
	R[low]=pivot;
	return low;
}
void QuickSort(SeqRecList R,int low,int high)
{
	int i;
	if(low<high)
	{
		i=Partition(R,low,high);
		QuickSort(R,low,i-1);
		QuickSort(R,i+1,high);
	}
}
int main()
{
	int i;
	SeqRecList q;
	for(i=0;i<MAX;i++)
	{
		q[i].key=MAX-i;
		q[i].otheritems='b'+i;
	}
	QuickSort(q,0,49);
	for(i=0;i<MAX;i++)
	{
		printf("%d\n",q[i].key);
	}
	return 0;
}
本人亲自测试通过

下面贴下百度的c++的快速排序算法

#include <iostream>
#include <cstdlib> // srand() 以及 rand()
#include <ctime> // time()
using namespace std;
int partion(int a[],int p,int r)
{
    //rand
    srand((unsigned)time( NULL));
    int e=rand()%(r-p+1)+p;
    int tem;
    tem=a[e];
    a[e]=a[r];
    a[r]=tem;
    int x=a[r], i=p-1;
    for (int j=p;j<r;j++)
	{
        if (a[j]<=x)
		{
            tem=a[i+1];
            a[i+1]=a[j];
            a[j]=tem;
            i++;
        }
    }
    tem=a[r];
    a[r]=a[i+1];
    a[i+1]=tem;
    return i+1;
}
void QuickSort(int a[],int p,int r)
{
    if (p<r){
        int q=partion(a,p,r);
        QuickSort(a,p,q-1);
        QuickSort(a,q+1,r);
    }
}
int main()
{
    int array[]={0,-2,11,-4,13,-5,14,-43};
    QuickSort(array,0,7);
    for(int i=0;i<=7;i++)
        cout<<array[i]<<" ";
    cout<<endl;
    return 0;
 }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值