动图展示
算法时间复杂度o(n*logn)
C++
//============================================================================
// Name : quicksort.cpp
// Author : YL
// Version :
//============================================================================
#include <iostream>
#define ArrayLen 10
using namespace std;
void QuickSort(int* array,int left, int right);
void swap(int* array, int i ,int j);
int SetPortitionIndex(int*array, int left, int right);
int main() {
int array[ArrayLen] = {5,2,3,9,6,8,1,4,7,0};
int left = 0;
int right = ArrayLen-1;
QuickSort(array,left, right);
for(int i = 0;i<ArrayLen;i++)
{
cout<<array[i]<<endl;
}
return 1;
}
void QuickSort(int* array, int left, int right)
{
int* local_array = array;
int IndexBaseline;
if (left<right)
{
IndexBaseline = SetPortitionIndex(local_array, left, right);
QuickSort(local_array, left, IndexBaseline-1);
QuickSort(local_array, IndexBaseline+1, right);
}
}
int SetPortitionIndex(int*array, int left, int right)
{
int* local_array = array;
int Baseline = left;
int Index = Baseline + 1;
for(int i =Index; i<=right; i++)
{
if (local_array[i]<local_array[Baseline])
{
swap(local_array,i, Index);
Index ++;
}
}
swap(local_array, Baseline, Index-1);
return Index -1;
}
void swap(int* array, int i ,int j)
{
int* local_array = array;
int temp;
temp = local_array[i];
local_array[i] = local_array[j];
local_array[j] = temp;
}
Python
#快速排序的思想:设置一个基准,对基准左右两边进行分别的排序
__author__ = '__yuanlei__'
def QuickSort(array, left, right):
if left < right:
#第一步定好那个基准
#然后在基准的左边右边用递归的形式使用QuickSort
IndexBaseline = ZoneDivision(array, left, right)
#表示当前Indexbaseline的值就是一个中间值,不用再Sort
#所以下面两个函数的结束和开始为IndexBaseline-1 和 IndexBaseline+1
QuickSort(array, left, IndexBaseline-1)
QuickSort(array, IndexBaseline+1, right)
return array
def ZoneDivision(array, left, right):
baseline = left
index = baseline + 1
for i in range(index, right+1):
if array[i]<array[baseline]:
array[i], array[index] = array[index], array[i]
index = index + 1
# 这个时候index相当于已经到了这个分解点,此时就要把当前baseline和index-1处的数进行交换
# 交换的目的就是把baseline对应的值放到此次分区的最右边
array[baseline],array[index-1] = array[index-1],array[baseline]
#最终返回的是当前次分区的分区索引
return index-1
if __name__ == '__main__':
inputarray = [7,1,4,2,3,6,5,0,9,8]
left = 0
right = len(inputarray)-1
output = QuickSort(inputarray,left,right)
print(output)