快速排序
代码来源–趣学算法第3章
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<stdbool.h>
#include<algorithm>
using namespace std;
int Partition(int r[], int low, int high)
{
int i = low;
int j = high;
int pivot = r[low];
while (i < j)
{
while (i<j && r[j] >pivot)
j--;
if (i < j)
{
swap(r[i++], r[j]);
}
while (i < j && r[i] <= pivot)
i++;
if (i < j)
{
swap(r[i], r[j--]);
}
}
return i;
}
int Partion2(int r[], int low, int high)
{
int i = low, j = high, pivot = r[low];
while (i < j)
{
while (i<j && r[j]>pivot)
j--;
while (i < j && r[i] <= pivot)
i++;
if (i < j)
{
swap(r[i++], r[j--]);
}
}
if (r[i] > pivot)
{
swap(r[i - 1].r[low]);
return i - 1;
}
swap(r[i], r[low]);
return i;
}
void QuickSort(int R[], int low, int high)
{
int mid;
if (low < high)
{
mid = Partition(R, low, high);
QuickSort(R, low, mid - 1);
QuickSort(R, mid + 1, high);
}
}
int main()
{
int a[1000];
int i, n;
printf("请输入要排序的数据的个数:\n");
scanf("%d", &n);
printf("请输入要排序的数据;\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("\n");
QuickSort(a, 0, n - 1);
printf("排序后的序列为:\n");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
后记
这里是用c写的,其实都差不多。