日常说明:有错误欢迎大家指正。另外本博客所有的代码博主编写后均调试通过。重要提醒!!!!博主使用的是VS2017,如果有低版本的小伙伴最好新建空项目将此代码复制上去。
更多算法请关注我的算法专栏https://blog.csdn.net/column/details/20417.html
运行结果:
为了更加熟练顺序表的操作,所以我选择了自己写顺序表。直接调用也是可以的。
QuickSort.h
#pragma once
#define LIST_INIT_SIZE 20;
#define INCREMENT 10
#include<iostream>
using namespace std;
template <class T>
class List
{
public:
List();
~List();
void List_Insert(int n, int values[]);
int quick_sort_part(List&, int low, int high);
void QuickSort(List&, int low, int high);
//
//private:
T * elem;
int length;
int list_size;
};
QuickSort.cpp
#include "QuickSort.h"
template<class T>
List<T>::List()
{
this->list_size = LIST_INIT_SIZE;
this->elem = new T(list_size);
this->elem[0] = 0;
this->length = 1;
}
template <class T>
List<T>::~List()
{
delete[]this->elem;
}
template<class T>
void List<T>::List_Insert(int n, int values[])
{
if (this->length >= this->list_size)//扩容
{
this->length += INCREMENT;
this->elem = new T(this->length);
}
for (int i = 1; i <= n; i++)//将数组中的元素一次赋值到顺序表
{
this->elem[i] = values[i];
length++;
}
}
template<class T>
int List<T>::quick_sort_part(List&list,int low,int high)
{
list.elem[0] = list.elem[low];
T pivot = list.elem[low];
while (low<high)
{
while (low<high && list.elem[high] >= pivot)
{
--high;
}
list.elem[low] = list.elem[high];
while (low<high&&list.elem[low]<=pivot)
{
++low;
}
list.elem[high] = this->elem[low];
}
list.elem[low] = list.elem[0];
return low;
}
template<class T>
void List<T>::QuickSort(List&list,int low,int high)
{
if (low < high)
{
int pivot_part = list.quick_sort_part(list, low, high);
QuickSort(list, low, pivot_part - 1);
QuickSort(list, pivot_part + 1,high);
}
}
int main()
{
List<int>list;
int n;
cout << "需要输入的数据个数:";
cin >> n;
int *values;
values = new int(n);
cout << endl;
cout << "请输入" << n << "个数据元素:";
for (int i = 1; i <= n; i++)
{
cin >> values[i];
}
list.List_Insert(n, values);
int low = 1;
int high = list.length - 1;
list.QuickSort(list,low,high);
cout << "快速排序后结果为:";
for (int i = 1; i <= n; i++)
{
cout << list.elem[i] << " ";
}
cout << endl;
return 0;
}