快速排序 算法

递归分治思想

快速排序限制条件很严格

#include 
void sort(int begin, int end,int *a);
int main() {
	int n;
	int a[100001];
	scanf("%d",&n);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
	}
	sort(1, n,a);

	for (int i = 1; i <= n; i++) {
		printf("%d ", a[i]);
	}
	return 0;
}
void sort(int begin,int end,int* a) {

	if (begin>=end) {
		return;
	}
	int temp = a[begin];   //这里以第一个为基准
	int i = begin;
	int j = end;
	while (i != j) {
		
		while (a[j] >= temp && i < j)j--;  
		//必须从从右开始,且最后赋值用i
		while (a[i] <= temp && i < j) i++;
		if (i < j) {
			int t = a[i];
			a[i] = a[j];
			a[j] = t;
		}
	}	
	a[begin] = a[i];
	a[i] = temp;
	sort(begin,i-1 ,a);
	sort(i + 1,end,a);
}
#include "stdio.h"
void Quick_Sort(int* arr, int begin, int end) {
    if (begin > end)
        return;
    int tmp = arr[begin];
    int i = begin;
    int j = end;
    while (i != j) {
        while (arr[j] >= tmp && j > i)
            j--;
        arr[i] = arr[j];           //填坑
        while (arr[i] <= tmp && j > i)
            i++;
        arr[j] = arr[i];           //填坑
       
    }
   
    arr[i] = tmp;            //填上最后相遇的坑
    Quick_Sort(arr, begin, i - 1);
    Quick_Sort(arr, i + 1, end);
}


int main() {
    int n;
    int a[100001];
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &a[i]);
    }
    Quick_Sort(a, 1,n);

    for (int i = 1; i <= n; i++) {
        printf("%d", a[i]);
    }

    return 0;
}

第二种,填坑法

你可能感兴趣的:(算法,排序算法)