快排(时间复杂度 nlgn)
一个非随机快排的实现:
#include <iostream>
#define arr_size 100 //数组元素个数100
using namespace std;
template<typename T>
void quick_sort(T A[],int low,int high){ //对T类数组快排(非随机快排)
if(low<high){
int index=low;
T temp;
for(int i=low;i<high;i++){
if(A[i]<=A[high]){ //比A[high]小的放左边
temp=A[i];
A[i]=A[index];
A[index]=temp;
index++; //指向第一个比A[high]大的元素
}
}
temp=A[high];
A[high]=A[index];
A[index]=temp;
quick_sort(A,low,index-1);
quick_sort(A,index+1,high);
}
}
int main(){
int a[arr_size]={0};
int i=0,j=0;
for(;cin>>a[i];i++){} //Ctrl+Z停止输入
quick_sort(a,0,i-1);
for(j=0;j<i;j++) cout<<a[j]<<' ';
return 0;
}
TOP K(时间复杂度 约为n)
快排思想的TOP K:
#include <iostream>
#define arr_size 100
using namespace std;
template<typename T>
void Quick_Search(T A[],int k,int low,int high){
if(low<high){
int index=low;
T temp;
for(int i=low;i<high;i++){
if(A[i]>=A[high]){
temp=A[i];
A[i]=A[index];
A[index]=temp;
index++;
}
}
temp=A[high];
A[high]=A[index];
A[index]=temp;
if(index==k-1) return; //如果index的值为k-1,那么A[index]就是第K大,它左边的就是TOP K-1
else if(index<k) Quick_Search(A,k-index-1,index+1,high);
else Quick_Search(A,k,low,index-1);
}
}
int main(){
int a[arr_size]={0};
int k=1;
cin>>k;
int i=0,j=0;
for(;cin>>a[i];i++){}
Quick_Search(a,k,0,i-1);
cout<<"The Kth Largest is:"<<a[k-1]<<endl;
for(j=0;j<k;j++) cout<<a[j]<<' ';
return 0;
}
最大子数组(时间复杂度 n)
定义max=A[0],sum=0;如果sum的值与即将到来的值A[i]的和大于0,则sum=sum+A[i],如果sum现在的值比max大,则将max的值替换为sum;否则sum值赋0:
#include <iostream>
#define arr_size 100
using namespace std;
template<typename T>
T Largest_Sum_of_Subarray(T A[],int a_size){
T max=A[0],sum=0;
for(int i=0;i<a_size;i++){
if(sum+A[i]>0) {
sum+=A[i];
if(sum>max) max=sum;
}
else sum=0;
}
return max;
}
int main(){
int a[arr_size];
int i=0;
for(;cin>>a[i];i++){}
cout<<Largest_Sum_of_Subarray(a,i)<<endl;
return 0;
}