快速排序

来源:互联网 发布:centos虚拟机怎么改ip 编辑:程序博客网 时间:2024/05/20 17:42

时间复杂度:nlogn

不稳定排序,

#include <iostream>using namespace std;void print(int a[], int n){int i = 1;for (; i < n; ++i){cout << a[i] << " ";}cout << endl;}int Partition(int a[], int low, int high){a[0] = a[low];while(low < high){while(low < high && a[high] < a[0]){--high;}a[low] = a[high];while(low < high && a[low] > a[0]){++low;}a[high] = a[low];}a[low] = a[0];return low;}void quickSort(int a[], int low, int high){int pos = 0;if (low < high){pos = Partition(a, low, high);quickSort(a, low, pos - 1);quickSort(a, pos + 1, high);}}int main(int argc, char argv[]){int a[] = {1, 32, 23, 53, 20, 98, 24, 542};int len = sizeof(a)/sizeof(int) - 1;cout << "before sort:" << endl;print(a, len);quickSort(a, 1, len);cout << "after sort: " << endl;print(a, len);}


原创粉丝点击