1. 程式人生 > >三種簡單排序-冒泡,插入,快速

三種簡單排序-冒泡,插入,快速

冒泡和插入都是巢狀兩個for迴圈實現:

冒泡:

for(int i=0;i<len-1;i++)
{
    for(int j=0;j<len-1-i;j++)
    {
        if(store[j]>store[j+1])
        swap(store[j],store[j+1]);
    }
}

插入:

for(int i=1;i<len-1;i++)
{
    int j;
    temp=store[i];
    for(j=i-1;store[j]>temp&&j>=0;j--)
    {
        swap(store[j],store[j+1]);
    }
    store[i+1]=temp;
}

快速:

int Part(int *reserve,int left,int right)
{
    int l_flag=left;
    temp=reserve[left];
    while(left<right)
    {
        while((left<right)&&(reserve[right]<=temp))right--;
        while((left<right)&&(reserve[left]>=temp))left++;
        if(left<right)
            swap(reserve[left],reserve[right]);
    }
    reserve[l_flag]=reserve[left];
    reserve[left]=temp;
    return left;
    
}
void quickSort(int *reserve,int left,int right)
{
    if(left<right)
    {
        int index=Part(reserve,left,right);
        quickSort(reserve,left,index-1);
        quickSort(reserve,index+1,right);
    }
}

最後所有的:

//冒泡
#include<stdio.h>
#include<vector>
using namespace std;
#define len  6
int temp;
void sort(int *reserve)
{
	for(int i=0;i<len-1;i++)
	{
		for(int j=0;j<len-1-i;j++)
		{
			if(reserve[j]>reserve[j+1])
			{
				temp=reserve[j+1];
				reserve[j+1]=reserve[j];
				reserve[j]=temp;
			}
		}
	}
}
void show(int *reserve)
{
	for(int i=0;i<len;i++)
		printf("%d ",reserve[i]);
	printf("\n");
}

///////////////////////////////////////////////
//插入
void insertSort(int *reserve)
{
	int i;
	for(int j=1;j<len;j++)
	{
		temp=reserve[j];
		for(i=j-1;i>=0&&reserve[i]>temp;i--)
		{
			reserve[i+1]=reserve[i];
		}
		reserve[i+1]=temp;
	}

}
////////////////////////////////////////////////
//快速
int Part(int *reserve,int left,int right)//取一個支點
{
	int key=reserve[left];
	int l_flag=left;//記錄下標
	while(left<right)
	{
		while(reserve[right]>=key&&right>left)right--;
		while(reserve[left]<=key&&left<right)left++;
		
		if(left<right)
		{
			temp=reserve[right];
			reserve[right]=reserve[left];
			reserve[left]=temp;
		}
	}
	reserve[l_flag]=reserve[left];
	reserve[left]=key;
	return left;
}
void quickSort(int *reserve,int left,int right)
{
	if(left<right)
	{
		int index=Part(reserve,left,right);
		quickSort(reserve,left,index-1);
		quickSort(reserve,index+1,right);
	}
}
///////////////////////////////////////////////////

int main()
{
	//vector store;
	int store[len]={3,1,4,2,6,5};
	sort(store);
	insertSort(store);
	quickSort(store,0,5);
	show(store);
	return 0;
}