交换排序--(冒泡排序和快速排序)

冒泡排序的主要思想是:轻的在上面,重的在下面,每次循环先把最轻的冒到顶端。

 

// 冒泡排序.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
using namespace std;

void insert(int data[],int key)
{
    for (int i = 0; i < key; i++)//开始key-1次循环  每一次循环得到最大的元素
    {
        for (int j = 1;j<key - i;j++)//比较得出最大的元素  并将其储存到data[j]位置
        {
            if (data[j] <data[j-1])
            {
                int temp = data[j];
                data[j] = data[j-1];
                data[j-1] = temp;
            }
        }
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    int array[10]={4,10,9,8,7,6,5,15,3,2};
    for (int i = 0; i < 10; i++)
    {
        cout<<array[i]<<"  ";
    }
    cout<<endl;
    insert(array,10);
    for (int i = 0; i < 10; i++)
    {
        cout<<array[i]<<"  ";
    }
    while (true)
    {

    }
    return 0;
}

 

 快速排序:

 

// 快速排序.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
using namespace std;

int insert(int data[],int left,int right)
{
    int min = data[left];//选取基准元素
    while (left < right)
    {
        while (left <right && min<= data[right])//将比基准值小的元素移到左边
        {
            right--;  
        }
            data[left]=data[right];
        while (left <right && min>= data[left])//讲比基准值大的元素移到右边
        {
            left++;
        }
            data[right]=data[left];
    }
    data[left] = min;
    return left;

}

void QuickSort(int data[],int left,int right)
{
    if (left <right)
    {
        int Num = insert(data,left,right);
        QuickSort(data,left,Num-1);
        QuickSort(data,Num+1,right);
    }
    
}

int _tmain(int argc, _TCHAR* argv[])
{
    int array[10]={4,10,9,8,7,6,5,15,3,2};
    for (int i = 0; i < 10; i++)
    {
        cout<<array[i]<<"  ";
    }
    cout<<endl;
    QuickSort(array,0,9);
    for (int i = 0; i < 10; i++)
    {
        cout<<array[i]<<"  ";
    }
    while (true)
    {

    }
    return 0;
}

 

 PS:实例代码在VS2010上验证通过

 

转载于:https://www.cnblogs.com/Visualize/archive/2012/08/23/2652420.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值