int数组快速排序

照着书上的代码,把C语言的改成了C++,把泛型指针改成了普通的int数组

#include <iostream>
#include <stdlib.h>

using namespace std;

class Solution {
public:
    int my_qsort(int A[], int n, int i, int k) {
		int j;
		while (i<k){
			if ((j = partition(A,i,k))<0)
				return -1;

			if (my_qsort(A,n,i,j)<0)
				return -1;

			i = j+1;// Iterate and sort the right partition
		}
    }
	int partition(int A[], int i, int k){
		int r[3],mid;
		r[0]=rand()%(k-i+1)+i;
		r[1]=rand()%(k-i+1)+i;
		r[2]=rand()%(k-i+1)+i;
		insert_sort(r,3);
		mid = A[ r[1] ];

		i--;k++;
		while(1){
			do{	k--	;}while(compare(A[k],mid)>0);
			
			do{	i++	;}while(compare(A[i],mid)<0);

			if(i>=k){
				break;
			}else{
				int tmp;
				tmp = A[k];
				A[k] = A[i];
				A[i] = tmp;
			}
		}
		return k;
	}
	void insert_sort(int r[], int size){
		if (size<=1)
			return;
		int i, j, pre=0;
		for (j=1;j<size;j++){
			i=j-1;
			int key = r[j];
			while(i>=0 && compare(r[i],key)>0){
				r[i+1] = r[i];
				i--;
			}//then the key pos is found
			r[i+1] = key;			
		}
	}
	int compare(int a1, int key){
		if (a1<key)
			return -1;// key pos is found
		else if(a1>key)
			return 1;
		else
			return 0;
	}
};

int main()
{
	Solution mySolution;
	int A[]={1,6,3,5,7,2,0,4},array_size = 8;
	mySolution.my_qsort(A,array_size,0,array_size-1);

	int i;
	for (i=0;i<array_size;i++)
		cout<<A[i]<<' ';

	cout <<endl;
	system("pause");
	return 0;
}

参考资料: 《算法精解——C语言描述》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
int数组快速排序可以通过递归实现。下面是一个示例的C++代码: ```cpp #include <iostream> // 交换数组中两个元素的位置 void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } // 将数组划分为两个部分,返回基准元素正确排序后的下标 int partition(int arr[], int low, int high) { // 选择最右边的元素作为基准 int pivot = arr[high]; int i = low - 1; for (int j = low; j <= high - 1; j++) { // 如果当前元素小于等于基准,将其放入左侧部分 if (arr[j] <= pivot) { i++; swap(&arr[i], &arr[j]); } } // 将基准元素放在正确的位置上 swap(&arr[i + 1], &arr[high]); return i + 1; } // 使用快速排序算法对数组进行排序 void quickSort(int arr[], int low, int high) { if (low < high) { // 将数组划分为两个部分 int pivot = partition(arr, low, high); // 递归地对左侧部分和右侧部分进行排序 quickSort(arr, low, pivot - 1); quickSort(arr, pivot + 1, high); } } int main() { int arr[] = {3, 9, 1, 4, 7, 2, 8, 6, 5}; int n = sizeof(arr) / sizeof(arr[0]); std::cout << "Original array: "; for (int i = 0; i < n; i++) { std::cout << arr[i] << " "; } std::cout << std::endl; // 对数组进行快速排序 quickSort(arr, 0, n - 1); std::cout << "Sorted array: "; for (int i = 0; i < n; i++) { std::cout << arr[i] << " "; } std::cout << std::endl; return 0; } ``` 这段代码实现了快速排序算法。首先,通过`partition`函数将数组划分为两个部分,并返回基准元素的正确位置。然后,对两个部分分别进行递归地排序,直到数组完全有序。在`main`函数中,我们可以看到一个示例数组的排序结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值