快速排序

简单
不说废话
直接放代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
using namespace std;

#define MAXSIZE 200

typedef struct {
	int r[MAXSIZE+1];
	int length;
} SqList;


int Partition (SqList &L,int low, int high){
	L.r[0]=L.r[low]; //子表的第一个记录作基准对象
	int pivotkey=L.r[low]; //基准对象关键字
	while (low<high){
		while (low<high && L.r[high]>=pivotkey) --high;
		L.r[low]=L.r[high]; //小于基准对象的移到区间的左侧
		while (low<high && L.r[low]<=pivotkey) ++low;
		L.r[high]=L.r[low]; //大于基准对象的移到区间的右侧
	}
	L.r[low]=L.r[0];
	return low;
}//Partition

void QSort ( SqList &L, int low, int high ) {
//在序列low..high 中递归地进行快速排序
	if ( low < high) {
		int pivotloc= Partition (L, low, high);   //划分

		QSort ( L, low, pivotloc-1); //对左序列同样处理
		QSort ( L, pivotloc+1, high); //对右序列同样处理
	}
}//QSort
void QuickSort (SqList &L) {//从0到L.length 
	QSort(L,0,L.length);
}//QuickSort


int main() {
	srand(time(0));
	SqList L;
	L.length=100;
	for(int i=1; i<=100; i++) {
		L.r[i]=rand()%100;
	}
	for(int i=1; i<=100; i++) {
		cout<<L.r[i]<<" ";
	}
	puts("");
	QuickSort (L);
	for(int i=1; i<=100; i++) {
		cout<<L.r[i]<<" ";
	}
	puts("") ;
	return 0;
}

简单的版本:

void quick_sort(int *arr, int begin, int end)
{
    if (begin < end) {
        int left = begin;
        int right = end;
        int thres = arr[left];
        while (left < right) {
            
            while (right > left && arr[right] >= thres)
                right--;
            arr[left] = arr[right];
            
            while (left < right && arr[left] < thres)
                left++;
            arr[right] = arr[left];
        }
        arr[left] = thres;   
        quick_sort(arr, begin, left - 1);
        quick_sort(arr, left + 1, end);   
    }
}

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 将给定数组排序
 * @param arr int整型一维数组 待排序的数组
 * @param arrLen int arr数组长度
 * @return int整型一维数组
 * @return int* returnSize 返回数组行数
 */
int* MySort(int* arr, int arrLen, int* returnSize ) {
    quick_sort(arr, 0, arrLen - 1);
    *returnSize = arrLen;
    return arr;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值