快速排序效率较高,采用分治策略,平均时间nlogn
主要使用了递归算法和子数组划分,关键之处在于子数组的划分问题上,由于在原址上进行数据的修改,不必合并子数组
直接上代码:
// QuickSort.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#define NUM 10
int ParticalSort(int a[], int begin, int end)
{
int pivot = a[end];
int i = begin-1;
int j = begin;
for (;j<end;++j)
{
if (a[j]<pivot)
{
++i;
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
for (int k = 0; k < NUM; ++k)
{
std::cout << a[k] << " ";
}
std::cout << std::endl;
}
int temp = a[j];
a[j] = a[i+1];
a[i + 1] = temp;
for (int k = 0; k < NUM; ++k)
{
std::cout << a[k] << " ";
}
std::cout << "\n-----------------------------------------" << std::endl;
return i+1;
}
void QuickSort(int a[],int begin,int end)
{
if (begin < end)
{
int pivot = ParticalSort(a, begin, end);
QuickSort(a, begin, pivot - 1);
QuickSort(a, pivot + 1, end);
}
}
int main()
{
int *a = new int[NUM];
for (int i = 0; i < NUM; ++i)
{
a[i] = rand() % NUM;
}
std::cout << "\n-----------------------------------------" << std::endl;
for (int i = 0; i < NUM;++i)
{
std::cout << a[i] << " ";
}
std::cout << "\n-----------------------------------------" << std::endl;
QuickSort(a, 0, NUM - 1);
std::cout << "\n-----------------------------------------" << std::endl;
for (int i = 0; i < NUM; ++i)
{
std::cout << a[i] << " ";
}
std::cout << "\n-----------------------------------------" << std::endl;
delete a;
return 0;
}