快速排序简单demo(C语言实现)

其中cout和cin类似于printf和scanf

#include<bits/stdc++.h>
using namespace std;

#define elementType int
typedef struct elem{
	elementType value;
}elem;

typedef struct quick{
	elem e[100];
	int lenght;
}quick;

void scan_Q(quick &Q){
	cout<<"请输入"<<Q.lenght<<"个元素。"<<endl; 
	for(int i = 0;i<Q.lenght;i++){
		cout<<"请输入第"<<i+1<<"个元素:"; 
		cin >> Q.e[i].value;
	}
}
void print_Q(quick Q){
	for(int i = 0;i<Q.lenght;i++){
		cout<<Q.e[i].value<<",";
	}
	cout<<endl;
}
void e_structer(quick &Q){//测试用构造器 
	Q.lenght = 10; 
	int a[] = {65,72,83,44,44,52,16,3,89,46};
	for(int i = 0;i<Q.lenght;i++){
		Q.e[i].value = a[i];
	}
}

void quick_sort(quick &Q,int start,int end){
	if(end-start<1)return;
	int low = start,high = end;
	elem e = Q.e[low];
	while(low != high){
		while((Q.e[high].value>=e.value) && low != high){high--;}
		Q.e[low] = Q.e[high];
		while((Q.e[low].value<=e.value) && low < high){low++;}
		Q.e[high] = Q.e[low];
	}
	Q.e[low] = e;
	quick_sort(Q,start,low-1);
	quick_sort(Q,high+1,end);
}



int main(){
	quick Q;
	int len = 0;
	cout<<"请输入待排序数列长度";
	cin>>len; 
	Q.lenght = len;
	
	scan_Q(Q);
	//	e_structer(Q);
	print_Q(Q);
	quick_sort(Q,0,Q.lenght-1);
	print_Q(Q);
	return 0;
} 

posted @ 2025-05-06 15:46  嘉君  阅读(14)  评论(0)    收藏  举报