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

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

 

// 冒泡排序.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上验证通过

 

posted @ 2012-08-23 14:38  subyafei  阅读(122)  评论(0编辑  收藏  举报