您的位置:首页 > 编程语言 > C语言/C++

quick sort 简单C++实现

2015-05-12 16:29 337 查看
// algorithms.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
using std::cout;
using std::endl;

void quickSort(int *a, int start, int end);
int partition(int *a, int start, int end);
void swap(int &i, int &j);
int main()
{
int a[10] = { 121, 22, 13, 34, 53, 62, 71, 48, 59, 104};

quickSort(a, 0, 9);

for (size_t i = 0; i < 10; i++)
{
cout << a[i] << " ";
}

return 0;
}

void swap(int &i, int &j){
int temp = i;
i = j;
j = temp;
}

void quickSort(int *a, int start, int end)
{
if (start < end)
{
int q = partition(a, start, end);
quickSort(a, start, q - 1);
quickSort(a, q + 1, end);
}
}

int partition(int *a, int start, int end)
{
int friendPar = a[end];
int i = start - 1;
for (int j = start; j <= end - 1;j++)
{
if (a[j]<friendPar)
{
++i;
swap(a[j], a[i]);
}
}
swap(a[++i], a[end]);
return i;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息