0
点赞
收藏
分享

微信扫一扫

Quick Sort (快速排序 C++)

Aliven888 2022-09-04 阅读 168


Below is the core code

template <class T>
int Partition(T a[], int p, int r){
int x = a[r];
int i = p - 1;
for(int j = p;j <= r - 1;j++){
if(a[j] <= x){
i++;
swap(a[i],a[j]);
}
}
swap(a[i + 1],a[r]);
return i + 1;
}


Figure below show how Partition works on an 8-element array.


Quick Sort (快速排序 C++)_i++

Array entry a[r] becomes the pivot element x. Lightly shaded array elements are all in the first partition with values no greater than x. Heavily shaded elements are in the second partition with values greater than x.

We compared the array entry a[j] and element x, if it  is greater than x, stay it along. So greater partition grows. However, if it  is smaller than x,  it and the first great element are swapped, the smaller partition grows. Continuing in this way. At last,  x element and the first great element are swapped. As a result, all left elements are small than x, all right elements are greater than x.

Quick Sort (快速排序 C++)_#include_02

// QuickSort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;


template <class T>
void PrintfNum(T a[], int n);

template <class T>
int Partition(T a[], int p, int r){
int x = a[r];
int i = p - 1;
for(int j = p;j <= r - 1;j++){
if(a[j] <= x){
i++;
swap(a[i],a[j]);
}
}
swap(a[i + 1],a[r]);
return i + 1;
}
template <class T>
void QuickSort(T a[], int p, int r){
if(p < r){
int q = Partition(a, p, r);
QuickSort(a, p, q - 1);
QuickSort(a, q + 1, r);
}
}

int main(int argc, char* argv[])
{
int a[8]={2,8,7,1,3,5,6,4};
cout << "Before sort:" << endl;
PrintfNum(a, 8);
cout << endl;

cout << "Partion Once:" << endl;
Partition(a, 0 ,7);
PrintfNum(a, 8);
cout << endl;

cout << "After sort:" << endl;
QuickSort(a, 0, 7);
PrintfNum(a, 8);
return 0;
}

template <class T>
void PrintfNum(T a[], int n){
for(int i = 0; i < n; i++){
cout << a[i] << ",";
}
cout << endl;
}


Result:

Quick Sort (快速排序 C++)_i++_03


Reference:

<INTRODUCTION TO ALGORITHMS> third edition


举报

相关推荐

0 条评论